@bsv/overlay 0.1.8 → 0.1.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 (80) hide show
  1. package/dist/cjs/package.json +2 -2
  2. package/dist/cjs/src/Engine.js +152 -492
  3. package/dist/cjs/src/Engine.js.map +1 -1
  4. package/dist/cjs/src/GASP/OverlayGASPRemote.js +6 -4
  5. package/dist/cjs/src/GASP/OverlayGASPRemote.js.map +1 -1
  6. package/dist/cjs/src/GASP/OverlayGASPStorage.js +152 -77
  7. package/dist/cjs/src/GASP/OverlayGASPStorage.js.map +1 -1
  8. package/dist/cjs/src/storage/knex/KnexStorage.js +106 -38
  9. package/dist/cjs/src/storage/knex/KnexStorage.js.map +1 -1
  10. package/dist/cjs/src/storage/knex/all-migrations.js +5 -1
  11. package/dist/cjs/src/storage/knex/all-migrations.js.map +1 -1
  12. package/dist/cjs/src/storage/knex/migrations/2024-07-17-001-transactions.js +39 -0
  13. package/dist/cjs/src/storage/knex/migrations/2024-07-17-001-transactions.js.map +1 -0
  14. package/dist/cjs/src/storage/knex/migrations/2024-07-18-001-indexes.js +34 -0
  15. package/dist/cjs/src/storage/knex/migrations/2024-07-18-001-indexes.js.map +1 -0
  16. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  17. package/dist/esm/src/Engine.js +150 -491
  18. package/dist/esm/src/Engine.js.map +1 -1
  19. package/dist/esm/src/GASP/OverlayGASPRemote.js +7 -4
  20. package/dist/esm/src/GASP/OverlayGASPRemote.js.map +1 -1
  21. package/dist/esm/src/GASP/OverlayGASPStorage.js +151 -77
  22. package/dist/esm/src/GASP/OverlayGASPStorage.js.map +1 -1
  23. package/dist/esm/src/storage/knex/KnexStorage.js +106 -38
  24. package/dist/esm/src/storage/knex/KnexStorage.js.map +1 -1
  25. package/dist/esm/src/storage/knex/all-migrations.js +5 -1
  26. package/dist/esm/src/storage/knex/all-migrations.js.map +1 -1
  27. package/dist/esm/src/storage/knex/migrations/2024-07-17-001-transactions.js +34 -0
  28. package/dist/esm/src/storage/knex/migrations/2024-07-17-001-transactions.js.map +1 -0
  29. package/dist/esm/src/storage/knex/migrations/2024-07-18-001-indexes.js +29 -0
  30. package/dist/esm/src/storage/knex/migrations/2024-07-18-001-indexes.js.map +1 -0
  31. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  32. package/dist/types/src/Engine.d.ts +8 -115
  33. package/dist/types/src/Engine.d.ts.map +1 -1
  34. package/dist/types/src/GASP/OverlayGASPRemote.d.ts +3 -2
  35. package/dist/types/src/GASP/OverlayGASPRemote.d.ts.map +1 -1
  36. package/dist/types/src/GASP/OverlayGASPStorage.d.ts +29 -3
  37. package/dist/types/src/GASP/OverlayGASPStorage.d.ts.map +1 -1
  38. package/dist/types/src/Output.d.ts +2 -2
  39. package/dist/types/src/Output.d.ts.map +1 -1
  40. package/dist/types/src/storage/Storage.d.ts +6 -8
  41. package/dist/types/src/storage/Storage.d.ts.map +1 -1
  42. package/dist/types/src/storage/knex/KnexStorage.d.ts +4 -4
  43. package/dist/types/src/storage/knex/KnexStorage.d.ts.map +1 -1
  44. package/dist/types/src/storage/knex/all-migrations.d.ts.map +1 -1
  45. package/dist/types/src/storage/knex/migrations/2024-07-17-001-transactions.d.ts +4 -0
  46. package/dist/types/src/storage/knex/migrations/2024-07-17-001-transactions.d.ts.map +1 -0
  47. package/dist/types/src/storage/knex/migrations/2024-07-18-001-indexes.d.ts +4 -0
  48. package/dist/types/src/storage/knex/migrations/2024-07-18-001-indexes.d.ts.map +1 -0
  49. package/dist/types/tsconfig.types.tsbuildinfo +1 -1
  50. package/package.json +2 -2
  51. package/src/Engine.ts +158 -550
  52. package/src/GASP/OverlayGASPRemote.ts +107 -0
  53. package/src/GASP/OverlayGASPStorage.ts +331 -0
  54. package/src/Output.ts +2 -2
  55. package/src/__tests/Engine.test.ts +27 -26
  56. package/src/__tests/OverlayGASPRemote.test.ts +1 -1
  57. package/src/__tests/OverlayGASPStorage.test.ts +4 -3
  58. package/src/storage/Storage.ts +6 -8
  59. package/src/storage/knex/KnexStorage.ts +119 -41
  60. package/src/storage/knex/all-migrations.ts +10 -6
  61. package/src/storage/knex/migrations/2024-07-17-001-transactions.ts +40 -0
  62. package/src/storage/knex/migrations/2024-07-18-001-indexes.ts +30 -0
  63. package/dist/cjs/src/GASP.js +0 -275
  64. package/dist/cjs/src/GASP.js.map +0 -1
  65. package/dist/cjs/src/SHIPAdvertisement.js +0 -3
  66. package/dist/cjs/src/SHIPAdvertisement.js.map +0 -1
  67. package/dist/cjs/src/SLAPAdvertisement.js +0 -3
  68. package/dist/cjs/src/SLAPAdvertisement.js.map +0 -1
  69. package/dist/esm/src/GASP.js +0 -279
  70. package/dist/esm/src/GASP.js.map +0 -1
  71. package/dist/esm/src/SHIPAdvertisement.js +0 -2
  72. package/dist/esm/src/SHIPAdvertisement.js.map +0 -1
  73. package/dist/esm/src/SLAPAdvertisement.js +0 -2
  74. package/dist/esm/src/SLAPAdvertisement.js.map +0 -1
  75. package/dist/types/src/GASP.d.ts +0 -215
  76. package/dist/types/src/GASP.d.ts.map +0 -1
  77. package/dist/types/src/SHIPAdvertisement.d.ts +0 -9
  78. package/dist/types/src/SHIPAdvertisement.d.ts.map +0 -1
  79. package/dist/types/src/SLAPAdvertisement.d.ts +0 -9
  80. package/dist/types/src/SLAPAdvertisement.d.ts.map +0 -1
@@ -1,5 +1,7 @@
1
- import { Transaction, MerklePath, isBroadcastFailure } from '@bsv/sdk';
1
+ import { Transaction, isBroadcastFailure } from '@bsv/sdk';
2
2
  import { GASP } from '@bsv/gasp';
3
+ import { OverlayGASPRemote } from './GASP/OverlayGASPRemote.js';
4
+ import { OverlayGASPStorage } from './GASP/OverlayGASPStorage.js';
3
5
  /**
4
6
  * Am engine for running BSV Overlay Services (topic managers and lookup services).
5
7
  */
@@ -14,6 +16,8 @@ export class Engine {
14
16
  broadcaster;
15
17
  advertiser;
16
18
  syncConfiguration;
19
+ logTime;
20
+ logPrefix;
17
21
  /**
18
22
  * Creates a new Overlay Services Engine
19
23
  * @param {[key: string]: TopicManager} managers - manages topic admittance
@@ -26,8 +30,10 @@ export class Engine {
26
30
  * @param {string} shipTrackers - SHIP domains we know to bootstrap the system
27
31
  * @param {string} slapTrackers - SLAP domains we know to bootstrap the system
28
32
  * @param {SyncConfiguration} syncConfiguration — Configuration object describing historical synchronization of topics.
33
+ * @param {boolean} logTime - Enables / disables the timing logs for various operations in the Overlay submit route.
34
+ * @param {string} logPrefix - Supports overriding the log prefix with a custom string.
29
35
  */
30
- constructor(managers, lookupServices, storage, chainTracker, hostingURL, shipTrackers, slapTrackers, broadcaster, advertiser, syncConfiguration) {
36
+ constructor(managers, lookupServices, storage, chainTracker, hostingURL, shipTrackers, slapTrackers, broadcaster, advertiser, syncConfiguration, logTime = false, logPrefix = '[OVERLAY_ENGINE] ') {
31
37
  this.managers = managers;
32
38
  this.lookupServices = lookupServices;
33
39
  this.storage = storage;
@@ -38,6 +44,8 @@ export class Engine {
38
44
  this.broadcaster = broadcaster;
39
45
  this.advertiser = advertiser;
40
46
  this.syncConfiguration = syncConfiguration;
47
+ this.logTime = logTime;
48
+ this.logPrefix = logPrefix;
41
49
  // To encourage synchronization of overlay services, the SHIP sync strategy is used by default for all overlay topics, except for 'tm_ship' and 'tm_slap'.
42
50
  // For these two topics, any existing trackers are combined with the provided shipTrackers and slapTrackers omitting any duplicates.
43
51
  if (syncConfiguration === undefined) {
@@ -71,6 +79,17 @@ export class Engine {
71
79
  }
72
80
  }
73
81
  }
82
+ // Helper functions for logging timings
83
+ startTime(label) {
84
+ if (this.logTime) {
85
+ console.time(`${this.logPrefix} ${label}`);
86
+ }
87
+ }
88
+ endTime(label) {
89
+ if (this.logTime) {
90
+ console.timeEnd(`${this.logPrefix} ${label}`);
91
+ }
92
+ }
74
93
  /**
75
94
  * Submits a transaction for processing by Overlay Services.
76
95
  * @param {TaggedBEEF} taggedBEEF - The transaction to process
@@ -90,70 +109,93 @@ export class Engine {
90
109
  // Validate the transaction SPV information
91
110
  const tx = Transaction.fromBEEF(taggedBEEF.beef);
92
111
  const txid = tx.id('hex');
93
- const txValid = await tx.verify(this.chainTracker); // Note: also verifying historical-tx with SPV. Needed?
112
+ this.startTime(`submit_${txid}`);
113
+ this.startTime(`chainTracker_${txid.substring(0, 10)}`);
114
+ const txValid = await tx.verify(this.chainTracker);
94
115
  if (!txValid)
95
116
  throw new Error('Unable to verify SPV information.');
96
- // Broadcast the transaction if not historical and broadcaster is configured
97
- if (mode !== 'historical-tx' && this.broadcaster !== undefined) {
98
- const response = await this.broadcaster.broadcast(tx);
99
- if (isBroadcastFailure(response)) {
100
- throw new Error(`Failed to broadcast transaction! Error: ${response.description}`);
101
- }
102
- }
103
- // Find UTXOs belonging to a particular topic
117
+ this.endTime(`chainTracker_${txid.substring(0, 10)}`);
104
118
  const steak = {};
105
- for (const topic of taggedBEEF.topics) {
106
- // Ensure transaction is not already applied to the topic
107
- const dupeCheck = await this.storage.doesAppliedTransactionExist({
108
- txid,
109
- topic
110
- });
119
+ let admissableOutputs = { outputsToAdmit: [], coinsToRetain: [] };
120
+ const previousCoins = [];
121
+ // Parallelize the topic processing
122
+ const topicPromises = taggedBEEF.topics.map(async (topic) => {
123
+ if (this.managers[topic] === undefined || this.managers[topic] === null) {
124
+ throw new Error(`This server does not support this topic: ${topic}`);
125
+ }
126
+ // Check for duplicate transactions
127
+ this.startTime(`dupCheck_${txid.substring(0, 10)}`);
128
+ const dupeCheck = await this.storage.doesAppliedTransactionExist({ txid, topic });
129
+ this.endTime(`dupCheck_${txid.substring(0, 10)}`);
111
130
  if (dupeCheck) {
112
- // The transaction was already processed.
113
- // Currently, NO OUTPUTS ARE ADMITTED FOR DUPLICATE TRANSACTIONS.
114
- // An alternative decision, one that was decided against, would be to act as if the operation was successful: looking up and returning the list of admitted outputs from when the transaction was originally processed.
115
- // This was decided against, because we don't want to encourage unnecessary flooding of duplicative transactions to overlay services.
116
- steak[topic] = {
117
- outputsToAdmit: [],
118
- coinsToRetain: []
119
- };
120
- continue;
131
+ steak[topic] = { outputsToAdmit: [], coinsToRetain: [] };
132
+ return;
121
133
  }
122
- // Check if any input of this transaction is a previous UTXO, adding previous UTXOs to the list
123
- const previousCoins = [];
124
- for (const [i, input] of tx.inputs.entries()) {
125
- const previousTXID = input.sourceTXID || input.sourceTransaction?.id('hex');
126
- // Check if a previous UTXO exists in the storage medium
127
- const output = await this.storage.findOutput(previousTXID, input.sourceOutputIndex, topic);
134
+ // Check if any input of this transaction is a previous UTXO
135
+ const outputPromises = tx.inputs.map(async (input, i) => {
136
+ const previousTXID = input.sourceTXID !== undefined ? input.sourceTXID : input.sourceTransaction?.id('hex');
137
+ if (previousTXID !== undefined) {
138
+ const output = this.storage.findOutput(previousTXID, input.sourceOutputIndex, topic);
139
+ if (output !== undefined && output !== null) {
140
+ previousCoins.push(i);
141
+ return await Promise.resolve(output);
142
+ }
143
+ }
144
+ return await Promise.resolve(null);
145
+ });
146
+ this.startTime(`previousOutputQuery_${txid.substring(0, 10)}`);
147
+ const outputs = await Promise.all(outputPromises);
148
+ this.endTime(`previousOutputQuery_${txid.substring(0, 10)}`);
149
+ const markSpentPromises = outputs.map(async (output) => {
128
150
  if (output !== undefined && output !== null) {
129
- previousCoins.push(i);
130
- // This output is now spent.
131
- await this.storage.markUTXOAsSpent(output.txid, output.outputIndex, topic);
132
- // Notify the lookup services about the spending of this output
133
- for (const l of Object.values(this.lookupServices)) {
134
- try {
135
- if (l.outputSpent !== undefined && l.outputSpent !== null) {
136
- await l.outputSpent(output.txid, output.outputIndex, topic);
151
+ try {
152
+ await this.storage.markUTXOAsSpent(output.txid, output.outputIndex, topic);
153
+ await Promise.all(Object.values(this.lookupServices).map(async (l) => {
154
+ try {
155
+ await l.outputSpent?.(output.txid, output.outputIndex, topic);
137
156
  }
138
- }
139
- catch (_) { }
157
+ catch (error) {
158
+ console.error('Error in lookup service for outputSpent:', error);
159
+ }
160
+ }));
161
+ }
162
+ catch (error) {
163
+ console.error('Error marking UTXO as spent:', error);
140
164
  }
141
165
  }
166
+ });
167
+ // Determine which outputs are admissible
168
+ const admissibleOutputsPromise = (async () => {
169
+ try {
170
+ this.startTime(`identifyAdmissibleOutputs_${txid.substring(0, 10)}`);
171
+ admissableOutputs = await this.managers[topic].identifyAdmissibleOutputs(taggedBEEF.beef, previousCoins);
172
+ this.endTime(`identifyAdmissibleOutputs_${txid.substring(0, 10)}`);
173
+ }
174
+ catch (_) {
175
+ steak[topic] = { outputsToAdmit: [], coinsToRetain: [] };
176
+ }
177
+ })();
178
+ // Wait for both tasks to complete
179
+ await Promise.all([markSpentPromises, admissibleOutputsPromise]);
180
+ // Keep track of what outputs were admitted for what topic
181
+ steak[topic] = admissableOutputs;
182
+ });
183
+ await Promise.all(topicPromises);
184
+ // Broadcast the transaction if not historical and broadcaster is configured
185
+ this.startTime(`broadcast_${txid.substring(0, 10)}`);
186
+ if (mode !== 'historical-tx' && this.broadcaster !== undefined) {
187
+ const response = await this.broadcaster.broadcast(tx);
188
+ if (isBroadcastFailure(response)) {
189
+ throw new Error(`Failed to broadcast transaction! Error: ${response.description}`);
142
190
  }
143
- // Use the manager to determine which outputs are admissable
144
- let admissableOutputs;
145
- try {
146
- admissableOutputs = await this.managers[topic].identifyAdmissibleOutputs(taggedBEEF.beef, previousCoins);
147
- }
148
- catch (_) {
149
- // If the topic manager throws an error, other topics may still succeed, so we continue to the next one.
150
- // No outputs were admitted to this topic in this case. Note, however, that the transaction is still valid according to Bitcoin, so it may have spent some previous overlay members. This is unavoidable and good.
151
- steak[topic] = {
152
- outputsToAdmit: [],
153
- coinsToRetain: []
154
- };
155
- continue;
156
- }
191
+ }
192
+ this.endTime(`broadcast_${txid.substring(0, 10)}`);
193
+ // Call the callback function if it is provided
194
+ if (onSteakReady !== undefined) {
195
+ this.endTime(`submit_${txid}`);
196
+ onSteakReady(steak);
197
+ }
198
+ for (const topic of taggedBEEF.topics) {
157
199
  // Keep track of which outputs to admit, mark as stale, or retain
158
200
  const outputsToAdmit = admissableOutputs.outputsToAdmit;
159
201
  const staleCoins = [];
@@ -177,16 +219,18 @@ export class Engine {
177
219
  }
178
220
  }
179
221
  // Remove stale outputs recursively
180
- for (const coin of staleCoins) {
222
+ this.startTime(`lookForStaleOutputs_${txid.substring(0, 10)}`);
223
+ await Promise.all(staleCoins.map(async (coin) => {
181
224
  const output = await this.storage.findOutput(coin.txid, coin.outputIndex, topic);
182
225
  if (output !== undefined && output !== null) {
183
226
  await this.deleteUTXODeep(output);
184
227
  }
185
- }
228
+ }));
229
+ this.endTime(`lookForStaleOutputs_${txid.substring(0, 10)}`);
186
230
  // Handle admittance and notification of incoming UTXOs
187
231
  const newUTXOs = [];
188
- for (const outputIndex of outputsToAdmit) {
189
- // Store the output
232
+ await Promise.all(outputsToAdmit.map(async (outputIndex) => {
233
+ this.startTime(`insertNewOutput_${txid.substring(0, 10)}`);
190
234
  await this.storage.insertOutput({
191
235
  txid,
192
236
  outputIndex,
@@ -198,51 +242,40 @@ export class Engine {
198
242
  consumedBy: [],
199
243
  outputsConsumed
200
244
  });
201
- newUTXOs.push({
202
- txid,
203
- outputIndex
204
- });
205
- // Notify all the lookup services about the new UTXO
206
- for (const l of Object.values(this.lookupServices)) {
207
- try {
208
- if (l.outputAdded !== undefined && l.outputAdded !== null) {
209
- await l.outputAdded(txid, outputIndex, tx.outputs[outputIndex].lockingScript, topic);
210
- }
245
+ this.endTime(`insertNewOutput_${txid.substring(0, 10)}`);
246
+ newUTXOs.push({ txid, outputIndex });
247
+ this.startTime(`notifyLookupService${txid.substring(0, 10)}`);
248
+ await Promise.all(Object.values(this.lookupServices).map(async (l) => await l.outputAdded?.(txid, outputIndex, tx.outputs[outputIndex].lockingScript, topic)));
249
+ this.endTime(`notifyLookupService${txid.substring(0, 10)}`);
250
+ }));
251
+ this.startTime(`outputConsumed_${txid.substring(0, 10)}`);
252
+ // Update each output consumed to know who consumed it and insert applied transaction in parallel
253
+ await Promise.all([
254
+ ...outputsConsumed.map(async (output) => {
255
+ const outputToUpdate = await this.storage.findOutput(output.txid, output.outputIndex, topic);
256
+ if (outputToUpdate !== undefined && outputToUpdate !== null) {
257
+ const newConsumedBy = [...new Set([...newUTXOs, ...outputToUpdate.consumedBy])];
258
+ await this.storage.updateConsumedBy(output.txid, output.outputIndex, topic, newConsumedBy);
211
259
  }
212
- catch (_) { }
213
- }
214
- }
215
- // Update each output consumed to know who consumed it
216
- for (const output of outputsConsumed) {
217
- const outputToUpdate = await this.storage.findOutput(output.txid, output.outputIndex, topic);
218
- if (outputToUpdate !== undefined && outputToUpdate !== null) {
219
- const newConsumedBy = [...new Set([...newUTXOs, ...outputToUpdate.consumedBy])];
220
- // Note: only update if newConsumedBy !== new Set(JSON.parse(outputToUpdate.consumedBy)) ?
221
- await this.storage.updateConsumedBy(output.txid, output.outputIndex, topic, newConsumedBy);
222
- }
223
- }
224
- // Insert the applied transaction to prevent duplicate processing
225
- await this.storage.insertAppliedTransaction({
226
- txid,
227
- topic
228
- });
229
- // Keep track of what outputs were admitted for what topic
230
- steak[topic] = admissableOutputs;
231
- }
232
- // Call the callback function if it is provided
233
- // TODO: To call `onSteakReady` sooner, we could have two loops. First we figure out topical admittance only, then we call `onSteakReeady` and do everything else after the first loop.
234
- if (onSteakReady !== undefined) {
235
- onSteakReady(steak);
260
+ }),
261
+ this.storage.insertAppliedTransaction({
262
+ txid,
263
+ topic
264
+ })
265
+ ]);
266
+ this.endTime(`outputConsumed_${txid.substring(0, 10)}`);
236
267
  }
237
268
  // If we don't have an advertiser or we are dealing with historical transactions, just return the steak
238
269
  if (this.advertiser === undefined || mode === 'historical-tx') {
239
270
  return steak;
240
271
  }
272
+ this.startTime(`transactionPropagation_${txid.substring(0, 10)}`);
241
273
  // Propagate transaction to other nodes according to synchronization agreements
242
274
  // 1. Find nodes that host the topics associated with admissable outputs
243
275
  // We want to figure out which topics we actually care about (because their associated outputs were admitted)
244
276
  // AND if the topic was not admitted we want to remove it from the list of topics we care about.
245
277
  const relevantTopics = taggedBEEF.topics.filter(topic => steak[topic] !== undefined && steak[topic].outputsToAdmit.length !== 0);
278
+ // TODO: Cache ship/slap lookup with expiry (every 5min)
246
279
  if (relevantTopics.length > 0) {
247
280
  // Find all SHIP advertisements for the topics we care about
248
281
  const domainToTopicsMap = new Map();
@@ -329,6 +362,7 @@ export class Engine {
329
362
  console.error('Error during broadcasting:', error);
330
363
  }
331
364
  }
365
+ this.endTime(`transactionPropgation_${txid.substring(0, 10)}`);
332
366
  // Immediately return from the function without waiting for the promises to resolve.
333
367
  return steak;
334
368
  }
@@ -341,7 +375,7 @@ export class Engine {
341
375
  // Validate a lookup service for the provider is found
342
376
  const lookupService = this.lookupServices[lookupQuestion.service];
343
377
  if (lookupService === undefined || lookupService === null)
344
- throw new Error(`Lookup service not found for provider: ${lookupQuestion.service}`);
378
+ throw new Error(`Lookup service not found for provider: ${lookupQuestion.service} `);
345
379
  let lookupResult = await lookupService.lookup(lookupQuestion);
346
380
  // Handle custom lookup service answers
347
381
  if (lookupResult.type === 'freeform' || lookupResult.type === 'output-list') {
@@ -351,12 +385,12 @@ export class Engine {
351
385
  const hydratedOutputs = [];
352
386
  for (const { txid, outputIndex, history } of lookupResult) {
353
387
  // Make sure this is an unspent output (UTXO)
354
- const UTXO = await this.storage.findOutput(txid, outputIndex, undefined, false);
388
+ const UTXO = await this.storage.findOutput(txid, outputIndex, undefined, undefined, true);
355
389
  if (UTXO === undefined || UTXO === null)
356
390
  continue;
357
391
  // Get the history for this utxo and construct a BRC-8 Envelope
358
392
  const output = await this.getUTXOHistory(UTXO, history, 0);
359
- if (output !== undefined && output !== null) {
393
+ if (output?.beef !== undefined) {
360
394
  hydratedOutputs.push({
361
395
  beef: output.beef,
362
396
  outputIndex: output.outputIndex
@@ -488,7 +522,7 @@ export class Engine {
488
522
  if (Array.isArray(syncEndpoints)) {
489
523
  await Promise.all(syncEndpoints.map(async (endpoint) => {
490
524
  // Sync to each host that is associated with this topic
491
- const gasp = new GASP(new OverlayGASPStorage(topic, this), new OverlayGASPRemote(endpoint, topic), 0, `[GASP Sync of ${topic} with ${endpoint}] `, true);
525
+ const gasp = new GASP(new OverlayGASPStorage(topic, this), new OverlayGASPRemote(endpoint, topic), 0, `[GASP Sync of ${topic} with ${endpoint}]`, true);
492
526
  await gasp.sync();
493
527
  }));
494
528
  }
@@ -528,7 +562,7 @@ export class Engine {
528
562
  */
529
563
  async provideForeignGASPNode(graphID, txid, outputIndex) {
530
564
  const hydrator = async (output) => {
531
- if (output === undefined || output === null) {
565
+ if (output?.beef === undefined) {
532
566
  throw new Error('No matching output found!');
533
567
  }
534
568
  const rootTx = Transaction.fromBEEF(output.beef);
@@ -606,6 +640,9 @@ export class Engine {
606
640
  if (typeof historySelector === 'undefined') {
607
641
  return output;
608
642
  }
643
+ if (output.beef === undefined) {
644
+ throw new Error('Output must have associated transaction BEEF!');
645
+ }
609
646
  // Determine if history traversal should continue for the current node
610
647
  let shouldTraverseHistory;
611
648
  if (typeof historySelector !== 'number') {
@@ -626,7 +663,7 @@ export class Engine {
626
663
  const outputsConsumed = output.outputsConsumed;
627
664
  // Find the child outputs for each utxo consumed by the current output
628
665
  const childHistories = (await Promise.all(outputsConsumed.map(async (outputIdentifier) => {
629
- const output = await this.storage.findOutput(outputIdentifier.txid, outputIdentifier.outputIndex);
666
+ const output = await this.storage.findOutput(outputIdentifier.txid, outputIdentifier.outputIndex, undefined, undefined, true);
630
667
  // Make sure an output was found
631
668
  if (output === undefined || output === null) {
632
669
  return undefined;
@@ -644,6 +681,9 @@ export class Engine {
644
681
  : input.sourceTransaction?.id('hex');
645
682
  return sourceTXID === output.txid && input.sourceOutputIndex === output.outputIndex;
646
683
  });
684
+ if (input.beef === undefined) {
685
+ throw new Error('Input must have associated transaction BEEF!');
686
+ }
647
687
  tx.inputs[inputIndex].sourceTransaction = Transaction.fromBEEF(input.beef);
648
688
  }
649
689
  const beef = tx.toBEEF();
@@ -655,9 +695,9 @@ export class Engine {
655
695
  catch (e) {
656
696
  // Handle any errors that occurred
657
697
  // Note: Test this!
658
- console.error(`Error retrieving UTXO history: ${e}`);
698
+ console.error(`Error retrieving UTXO history: ${e} `);
659
699
  // return []
660
- throw new Error(`Error retrieving UTXO history: ${e}`);
700
+ throw new Error(`Error retrieving UTXO history: ${e} `);
661
701
  }
662
702
  }
663
703
  /**
@@ -700,7 +740,7 @@ export class Engine {
700
740
  });
701
741
  }
702
742
  catch (error) {
703
- throw new Error(`Failed to delete all stale outputs: ${error}`);
743
+ throw new Error(`Failed to delete all stale outputs: ${error} `);
704
744
  }
705
745
  }
706
746
  /**
@@ -737,6 +777,9 @@ export class Engine {
737
777
  * @param proof - The merklePath proving txid is a mined transaction hash
738
778
  */
739
779
  async updateMerkleProof(output, txid, proof) {
780
+ if (output.beef === undefined) {
781
+ throw new Error('Output must have associated transaction BEEF!');
782
+ }
740
783
  const tx = Transaction.fromBEEF(output.beef);
741
784
  if (tx.merklePath !== undefined) {
742
785
  // Update the merkle path to handle potential reorgs
@@ -746,10 +789,10 @@ export class Engine {
746
789
  // recursively update all sourceTransactions proven by (txid,proof)
747
790
  this.updateInputProofs(tx, txid, proof);
748
791
  // Update the output's BEEF in the storage DB
749
- await this.storage.updateOutputBeef(output.txid, output.outputIndex, output.topic, tx.toBEEF());
792
+ await this.storage.updateTransactionBEEF(output.txid, tx.toBEEF());
750
793
  // Recursively update the consumedBy outputs
751
794
  for (const consumingOutput of output.consumedBy) {
752
- const consumedOutputs = await this.storage.findOutputsForTransaction(consumingOutput.txid);
795
+ const consumedOutputs = await this.storage.findOutputsForTransaction(consumingOutput.txid, true);
753
796
  for (const consumedOutput of consumedOutputs) {
754
797
  await this.updateMerkleProof(consumedOutput, txid, proof);
755
798
  }
@@ -763,7 +806,7 @@ export class Engine {
763
806
  * @param blockHeight - The block height associated with the incoming merkle proof.
764
807
  */
765
808
  async handleNewMerkleProof(txid, proof, blockHeight) {
766
- const outputs = await this.storage.findOutputsForTransaction(txid);
809
+ const outputs = await this.storage.findOutputsForTransaction(txid, true);
767
810
  if (outputs === undefined || outputs.length === 0) {
768
811
  throw new Error('Could not find matching transaction outputs for proof ingest!');
769
812
  }
@@ -819,389 +862,5 @@ There is currently a bug with the test runner that prevents importing and using
819
862
  Thus, all non-type exports have been moved to Engine.
820
863
  */
821
864
  // TODO: fix bug with imports that break tests. -----[GASP/OverlayGASPRemote.ts]-----
822
- export class OverlayGASPRemote {
823
- endpointURL;
824
- topic;
825
- constructor(endpointURL, topic) {
826
- this.endpointURL = endpointURL;
827
- this.topic = topic;
828
- }
829
- /**
830
- * Given an outgoing initial request, sends the request to the foreign instance and obtains their initial response.
831
- * @param request
832
- * @returns
833
- */
834
- async getInitialResponse(request) {
835
- // Send out an HTTP request to the URL (current host for topic)
836
- // Include the topic in the request
837
- // Parse out response and return correct format
838
- const url = `${this.endpointURL}/requestSyncResponse`;
839
- const response = await fetch(url, {
840
- method: 'POST',
841
- headers: {
842
- 'Content-Type': 'application/json',
843
- 'X-BSV-Topic': this.topic
844
- },
845
- body: JSON.stringify(request)
846
- });
847
- if (!response.ok) {
848
- throw new Error(`HTTP error! Status: ${response.status}`);
849
- }
850
- const result = await response.json();
851
- // Validate and return the response in the correct format
852
- if (!Array.isArray(result.UTXOList) || typeof result.since !== 'number') {
853
- throw new Error('Invalid response format');
854
- }
855
- return {
856
- UTXOList: result.UTXOList.map((utxo) => ({
857
- txid: utxo.txid,
858
- outputIndex: utxo.outputIndex
859
- })),
860
- since: result.since
861
- };
862
- }
863
- /**
864
- * Given an outgoing txid, outputIndex and optional metadata, request the associated GASP node from the foreign instance.
865
- * @param graphID
866
- * @param txid
867
- * @param outputIndex
868
- * @param metadata
869
- * @returns
870
- */
871
- async requestNode(graphID, txid, outputIndex, metadata) {
872
- // Send an HTTP request with the provided info and get back a gaspNode
873
- const url = `${this.endpointURL}/requestForeignGASPNode`;
874
- const body = {
875
- graphID,
876
- txid,
877
- outputIndex,
878
- metadata
879
- };
880
- const response = await fetch(url, {
881
- method: 'POST',
882
- headers: {
883
- 'Content-Type': 'application/json'
884
- },
885
- body: JSON.stringify(body)
886
- });
887
- if (!response.ok) {
888
- throw new Error(`HTTP error! Status: ${response.status}`);
889
- }
890
- const result = await response.json();
891
- // Validate and return the response in the correct format
892
- if (typeof result.graphID !== 'string' || typeof result.rawTx !== 'string' || typeof result.outputIndex !== 'number') {
893
- throw new Error('Invalid response format');
894
- }
895
- const gaspNode = {
896
- graphID: result.graphID,
897
- rawTx: result.rawTx,
898
- outputIndex: result.outputIndex,
899
- proof: result.proof,
900
- txMetadata: result.txMetadata,
901
- outputMetadata: result.outputMetadata,
902
- inputs: result.inputs
903
- };
904
- return gaspNode;
905
- }
906
- // ---- Now optional methods ----
907
- // When are only syncing to them
908
- async getInitialReply(response) {
909
- throw new Error('Function not supported!');
910
- }
911
- // Only used when supporting bidirectional sync.
912
- // Overlay services does not support this.
913
- async submitNode(node) {
914
- throw new Error('Node submission not supported!');
915
- }
916
- }
917
- export class OverlayGASPStorage {
918
- topic;
919
- engine;
920
- maxNodesInGraph;
921
- temporaryGraphNodeRefs = {};
922
- constructor(topic, engine, maxNodesInGraph) {
923
- this.topic = topic;
924
- this.engine = engine;
925
- this.maxNodesInGraph = maxNodesInGraph;
926
- }
927
- /**
928
- *
929
- * @param since
930
- * @returns
931
- */
932
- async findKnownUTXOs(since) {
933
- const UTXOs = await this.engine.storage.findUTXOsForTopic(this.topic, since);
934
- return UTXOs.map(output => ({
935
- txid: output.txid,
936
- outputIndex: output.outputIndex
937
- }));
938
- }
939
- /**
940
- * For a given txid and output index, returns the associated transaction, a merkle proof if the transaction is in a block, and metadata if if requested. If no metadata is requested, metadata hashes on inputs are not returned.
941
- * @param graphID
942
- * @param txid
943
- * @param outputIndex
944
- * @param metadata
945
- * @returns
946
- */
947
- async hydrateGASPNode(graphID, txid, outputIndex, metadata) {
948
- const output = await this.engine.storage.findOutput(txid, outputIndex);
949
- if (output === undefined || output === null) {
950
- throw new Error('No matching output found!');
951
- }
952
- const tx = Transaction.fromBEEF(output.beef);
953
- const rawTx = tx.toHex();
954
- const node = {
955
- rawTx,
956
- graphID,
957
- outputIndex
958
- };
959
- if (tx.merklePath !== undefined) {
960
- node.proof = tx.merklePath.toHex();
961
- }
962
- return node;
963
- }
964
- /**
965
- * For a given node, returns the inputs needed to complete the graph, including whether updated metadata is requested for those inputs.
966
- * @param tx The node for which needed inputs should be found.
967
- * @returns A promise for a mapping of requested input transactions and whether metadata should be provided for each.
968
- */
969
- async findNeededInputs(tx) {
970
- // If there is no Merkle proof, we always need the inputs
971
- const response = {
972
- requestedInputs: {}
973
- };
974
- const parsedTx = Transaction.fromHex(tx.rawTx);
975
- if (tx.proof === undefined) {
976
- for (const input of parsedTx.inputs) {
977
- response.requestedInputs[`${input.sourceTXID}.${input.sourceOutputIndex}`] = {
978
- metadata: false
979
- };
980
- }
981
- return await this.stripAlreadyKnownInputs(response);
982
- }
983
- // Attempt to check if the current transaction is admissible
984
- parsedTx.merklePath = MerklePath.fromHex(tx.proof);
985
- const admittanceResult = await this.engine.managers[this.topic].identifyAdmissibleOutputs(parsedTx.toBEEF(), []);
986
- if (admittanceResult.outputsToAdmit.includes(tx.outputIndex)) {
987
- // The transaction is admissible, no further inputs are needed
988
- }
989
- else {
990
- // The transaction is not admissible, get inputs needed for further verification
991
- // TopicManagers should implement a function to identify which inputs are needed.
992
- if (this.engine.managers[this.topic] !== undefined && typeof this.engine.managers[this.topic].identifyNeededInputs === 'function') {
993
- try {
994
- const neededInputs = await this.engine.managers[this.topic].identifyNeededInputs?.(parsedTx.toBEEF()) ?? [];
995
- for (const input of neededInputs) {
996
- response.requestedInputs[`${input.txid}.${input.outputIndex}`] = {
997
- metadata: false
998
- };
999
- }
1000
- return await this.stripAlreadyKnownInputs(response);
1001
- }
1002
- catch (e) {
1003
- console.error(`An error occurred when identifying needed inputs for transaction: ${parsedTx.id('hex')}.${tx.outputIndex}!`);
1004
- // Cut off the graph in case of an error here.
1005
- }
1006
- }
1007
- // By default, if the topic manager isn't able to stipulate needed inputs, only the inputs necessary for SPV are requested.
1008
- }
1009
- // Everything else falls through to returning undefined/void, which will terminate the synchronization at this point.
1010
- }
1011
- /**
1012
- * Ensures that no inputs are requested from foreign nodes before sending any GASP response
1013
- * Also terminates graphs if the response would be empty.
1014
- */
1015
- async stripAlreadyKnownInputs(response) {
1016
- if (typeof response === 'undefined') {
1017
- return response;
1018
- }
1019
- for (const inputNodeId of Object.keys(response.requestedInputs)) {
1020
- const [txid, outputIndex] = inputNodeId.split('.');
1021
- const found = await this.engine.storage.findOutput(txid, Number(outputIndex), this.topic);
1022
- if (found) {
1023
- delete response.requestedInputs[inputNodeId];
1024
- }
1025
- }
1026
- if (Object.keys(response.requestedInputs).length === 0) {
1027
- return undefined;
1028
- }
1029
- return response;
1030
- }
1031
- /**
1032
- * Appends a new node to a temporary graph.
1033
- * @param tx The node to append to this graph.
1034
- * @param spentBy Unless this is the same node identified by the graph ID, denotes the TXID and input index for the node which spent this one, in 36-byte format.
1035
- * @throws If the node cannot be appended to the graph, either because the graph ID is for a graph the recipient does not want or because the graph has grown to be too large before being finalized.
1036
- */
1037
- async appendToGraph(tx, spentBy) {
1038
- if (this.maxNodesInGraph !== undefined && Object.keys(this.temporaryGraphNodeRefs).length >= this.maxNodesInGraph) {
1039
- throw new Error('The max number of nodes in transaction graph has been reached!');
1040
- }
1041
- const parsedTx = Transaction.fromHex(tx.rawTx);
1042
- const txid = parsedTx.id('hex');
1043
- if (tx.proof !== undefined) {
1044
- parsedTx.merklePath = MerklePath.fromHex(tx.proof);
1045
- }
1046
- // Given the passed in node, append to the temp graph
1047
- // Use the spentBy param which should be a txid.inputIndex for the node which spent this one in 36-byte format
1048
- const newGraphNode = {
1049
- txid,
1050
- graphID: tx.graphID,
1051
- rawTx: tx.rawTx,
1052
- outputIndex: tx.outputIndex,
1053
- proof: tx.proof,
1054
- txMetadata: tx.txMetadata,
1055
- outputMetadata: tx.outputMetadata,
1056
- inputs: tx.inputs,
1057
- children: []
1058
- };
1059
- // If spentBy is undefined, then we know it's the root node.
1060
- if (spentBy === undefined) {
1061
- this.temporaryGraphNodeRefs[tx.graphID] = newGraphNode;
1062
- }
1063
- else {
1064
- // Find the parent node based on spentBy
1065
- const parentNode = this.temporaryGraphNodeRefs[spentBy];
1066
- if (parentNode !== undefined) {
1067
- // Set parent-child relationship
1068
- parentNode.children.push(newGraphNode);
1069
- newGraphNode.parent = parentNode;
1070
- this.temporaryGraphNodeRefs[`${newGraphNode.txid}.${newGraphNode.outputIndex}`] = newGraphNode;
1071
- }
1072
- else {
1073
- throw new Error(`Parent node with GraphID ${spentBy} not found`);
1074
- }
1075
- }
1076
- }
1077
- /**
1078
- * Checks whether the given graph, in its current state, makes reference only to transactions that are proven in the blockchain, or already known by the recipient to be valid.
1079
- * Additionally, in a breadth-first manner (ensuring that all inputs for any given node are processed before nodes that spend them), it ensures that the root node remains valid according to the rules of the overlay's topic manager,
1080
- * while considering any coins which the Manager had previously indicated were either valid or invalid.
1081
- * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the tip of this graph.
1082
- * @throws If the graph is not well-anchored, according to the rules of Bitcoin or the rules of the Overlay Topic Manager.
1083
- */
1084
- async validateGraphAnchor(graphID) {
1085
- const rootNode = this.temporaryGraphNodeRefs[graphID];
1086
- if (rootNode === undefined) {
1087
- throw new Error(`Graph node with ID ${graphID} not found`);
1088
- }
1089
- // Check that the root node is Bitcoin-valid.
1090
- const beef = this.getBEEFForNode(rootNode);
1091
- const spvTx = Transaction.fromBEEF(beef);
1092
- const isBitcoinValid = await spvTx.verify(this.engine.chainTracker);
1093
- if (!isBitcoinValid) {
1094
- throw new Error('The graph is not well-anchored according to the rules of Bitcoin.');
1095
- }
1096
- // Then, ensure the node is Overlay-valid.
1097
- const beefs = this.computeOrderedBEEFsForGraph(graphID);
1098
- // coins: a Set of all historical coins to retain (no need to remove them), used to emulate topical admittance of previous inputs over time.
1099
- const coins = new Set();
1100
- // Submit all historical BEEFs in order through the topic manager, tracking what would be retained until we submit the root node last.
1101
- // If, at the end, the root node is admitted, we have a valid overlay-specific graph.
1102
- for (const beef of beefs) {
1103
- // For any input to this transaction, see if it's a valid coin that's admitted. If so, it's a previous coin.
1104
- const previousCoins = [];
1105
- const tx = Transaction.fromBEEF(beef);
1106
- for (const inputIndex in tx.inputs) {
1107
- const input = tx.inputs[inputIndex];
1108
- const sourceTXID = input.sourceTXID || input.sourceTransaction?.id('hex');
1109
- const coin = `${sourceTXID}.${input.sourceOutputIndex}`;
1110
- if (coins.has(coin)) {
1111
- previousCoins.push(Number(inputIndex));
1112
- }
1113
- }
1114
- const admittanceInstructions = await this.engine.managers[this.topic].identifyAdmissibleOutputs(beef, previousCoins);
1115
- // Every admitted output is now a coin.
1116
- for (const outputIndex of admittanceInstructions.outputsToAdmit) {
1117
- coins.add(`${tx.id('hex')}.${outputIndex}`);
1118
- }
1119
- }
1120
- // After sending through all the graph's BEEFs...
1121
- // If the root node is now a coin, we have acceptance by the overlay.
1122
- // Otherwise, throw.
1123
- if (!coins.has(graphID)) {
1124
- throw new Error('This graph did not result in topical admittance of the root node. Rejecting.');
1125
- }
1126
- }
1127
- /**
1128
- * Deletes all data associated with a temporary graph that has failed to sync, if the graph exists.
1129
- * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the tip of this graph.
1130
- */
1131
- async discardGraph(graphID) {
1132
- for (const [nodeId, graphRef] of Object.entries(this.temporaryGraphNodeRefs)) {
1133
- if (graphRef.graphID === graphID) {
1134
- // Delete child node
1135
- // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
1136
- delete this.temporaryGraphNodeRefs[nodeId];
1137
- }
1138
- }
1139
- }
1140
- /**
1141
- * Finalizes a graph, solidifying the new UTXO and its ancestors so that it will appear in the list of known UTXOs.
1142
- * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the root of this graph.
1143
- */
1144
- async finalizeGraph(graphID) {
1145
- const beefs = this.computeOrderedBEEFsForGraph(graphID);
1146
- // Submit all historical BEEFs in order, finalizing the graph for the current UTXO
1147
- for (const beef of beefs) {
1148
- await this.engine.submit({
1149
- beef,
1150
- topics: [this.topic]
1151
- }, () => { }, 'historical-tx');
1152
- }
1153
- }
1154
- /**
1155
- * Computes an ordered set of BEEFs for the graph with the given graph IDs
1156
- * @param {string} graphID — The ID of the graph for which BEEFs are required
1157
- * @returns Ordered BEEFs for the graph
1158
- */
1159
- computeOrderedBEEFsForGraph(graphID) {
1160
- const beefs = [];
1161
- const hydrator = (node) => {
1162
- const currentBEEF = this.getBEEFForNode(node);
1163
- if (beefs.indexOf(currentBEEF) === -1) {
1164
- beefs.unshift(currentBEEF);
1165
- }
1166
- for (const child of node.children) {
1167
- // Continue backwards to the earliest nodes, adding them onto the beginning
1168
- hydrator(child);
1169
- }
1170
- };
1171
- // Start the hydrator with the root node
1172
- const foundRoot = this.temporaryGraphNodeRefs[graphID];
1173
- if (!foundRoot) {
1174
- throw new Error('Unable to find root node in graph for finalization!');
1175
- }
1176
- hydrator(foundRoot);
1177
- return beefs;
1178
- }
1179
- /**
1180
- * Computes a full BEEF for a given graph node, based on the temporary graph store.
1181
- * @param node Graph node for which BEEF is needed.
1182
- * @returns BEEF array, including all proofs on inputs.
1183
- */
1184
- getBEEFForNode(node) {
1185
- // Given a node, hydrate its merkle proof or all inputs, returning a reference to the hydrated node's Transaction object
1186
- const hydrator = (node) => {
1187
- const tx = Transaction.fromHex(node.rawTx);
1188
- if (node.proof) {
1189
- tx.merklePath = MerklePath.fromHex(node.proof);
1190
- return tx; // Transaction with proof, end of the line.
1191
- }
1192
- // For each input, look it up and recurse.
1193
- for (const inputIndex in tx.inputs) {
1194
- const input = tx.inputs[inputIndex];
1195
- const foundNode = this.temporaryGraphNodeRefs[`${input.sourceTXID}.${input.sourceOutputIndex}`];
1196
- if (!foundNode) {
1197
- throw new Error('Required input node for unproven parent not found in temporary graph store. Ensure, for every parent of any given already-proven node (kept for Overlay-specific historical reasons), that a proof is also provided on those inputs. While implicitly they are valid by virtue of their descendents being proven in the blockchain, BEEF serialization will still fail when winding forward the topical UTXO set histories during sync.');
1198
- }
1199
- tx.inputs[inputIndex].sourceTransaction = hydrator(foundNode);
1200
- }
1201
- return tx;
1202
- };
1203
- const finalTX = hydrator(node);
1204
- return finalTX.toBEEF();
1205
- }
1206
- }
865
+ // TODO: fix bug with imports that break tests. -----[GASP/OverlayGASPStorage.ts]-----
1207
866
  //# sourceMappingURL=Engine.js.map