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