@bsv/overlay 0.1.3 → 0.1.5

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.
package/src/Engine.ts CHANGED
@@ -11,7 +11,7 @@ import { LookupFormula } from './LookupFormula.js'
11
11
  import { Transaction, ChainTracker, MerklePath, Broadcaster, isBroadcastFailure } from '@bsv/sdk'
12
12
  import { Advertiser } from './Advertiser.js'
13
13
  import { SHIPAdvertisement } from './SHIPAdvertisement.js'
14
- import { GASP, GASPInitialReply, GASPInitialRequest, GASPInitialResponse, GASPNode, GASPNodeResponse, GASPRemote, GASPStorage } from '@bsv/gasp'
14
+ import { GASP, GASPInitialReply, GASPInitialRequest, GASPInitialResponse, GASPNode, GASPNodeResponse, GASPRemote, GASPStorage } from './GASP.js'
15
15
  import { SyncConfiguration } from './SyncConfiguration.js'
16
16
 
17
17
  /**
@@ -43,6 +43,13 @@ export class Engine {
43
43
  public advertiser?: Advertiser,
44
44
  public syncConfiguration?: SyncConfiguration
45
45
  ) {
46
+ // To encourage synchronization of overlay services, the SHIP sync strategy is used by default for all topics.
47
+ if (syncConfiguration === undefined) {
48
+ this.syncConfiguration = {}
49
+ for (const managerName of Object.keys(managers)) {
50
+ this.syncConfiguration[managerName] = 'SHIP'
51
+ }
52
+ }
46
53
  }
47
54
 
48
55
  /**
@@ -563,25 +570,66 @@ export class Engine {
563
570
  * @throws An error if no output is found for the given transaction ID and output index.
564
571
  */
565
572
  async provideForeignGASPNode(graphID: string, txid: string, outputIndex: number): Promise<GASPNode> {
566
- const output = await this.storage.findOutput(txid, outputIndex)
573
+ const hydrator = async (output: Output | null): Promise<GASPNode> => {
574
+ if (output === undefined || output === null) {
575
+ throw new Error('No matching output found!')
576
+ }
567
577
 
568
- if (output === undefined || output === null) {
569
- throw new Error('No matching output found!')
570
- }
578
+ const rootTx = Transaction.fromBEEF(output.beef)
579
+ let correctTx: Transaction | undefined
571
580
 
572
- const tx = Transaction.fromBEEF(output.beef)
573
- const rawTx = tx.toHex()
581
+ const searchInput = (tx: Transaction): void => {
582
+ if (tx.id('hex') === txid) {
583
+ correctTx = tx
584
+ } else {
585
+ // For each input, look it up and recurse.
586
+ for (const input of tx.inputs) {
587
+ // We should always have a source transaction
588
+ if (input.sourceTransaction !== undefined) {
589
+ searchInput(input.sourceTransaction)
590
+ } else {
591
+ throw new Error('Incomplete SPV data!')
592
+ }
593
+ }
594
+ }
595
+ }
574
596
 
575
- const node: GASPNode = {
576
- rawTx,
577
- graphID,
578
- outputIndex
579
- }
580
- if (tx.merklePath !== undefined) {
581
- node.proof = tx.merklePath.toHex()
597
+ searchInput(rootTx)
598
+
599
+ if (correctTx !== undefined) {
600
+ const rawTx = correctTx.toHex()
601
+ const node: GASPNode = {
602
+ rawTx,
603
+ graphID,
604
+ outputIndex
605
+ }
606
+ if (correctTx.merklePath !== undefined) {
607
+ node.proof = correctTx.merklePath.toHex()
608
+ }
609
+
610
+ return node
611
+ } else {
612
+ // Recursively try to find a matching output
613
+ let foundNode: GASPNode | undefined
614
+ for (const currentOutput of output.outputsConsumed) {
615
+ try {
616
+ const outputFound = await this.storage.findOutput(currentOutput.txid, currentOutput.outputIndex)
617
+ foundNode = await hydrator(outputFound)
618
+ break
619
+ } catch (error) {
620
+ continue
621
+ }
622
+ }
623
+ if (foundNode !== undefined) {
624
+ return foundNode
625
+ }
626
+ }
627
+ throw new Error('Unable to find output associated with your request!')
582
628
  }
583
629
 
584
- return node
630
+ const [rootTxid, rootOutputIndex] = graphID.split('.')
631
+ const output = await this.storage.findOutput(rootTxid, Number(rootOutputIndex))
632
+ return await hydrator(output)
585
633
  }
586
634
 
587
635
  /**
@@ -989,9 +1037,34 @@ export class OverlayGASPStorage implements GASPStorage {
989
1037
  }))
990
1038
  }
991
1039
 
992
- // TODO: Consider optionality on interface
1040
+ /**
1041
+ * 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.
1042
+ * @param graphID
1043
+ * @param txid
1044
+ * @param outputIndex
1045
+ * @param metadata
1046
+ * @returns
1047
+ */
993
1048
  async hydrateGASPNode(graphID: string, txid: string, outputIndex: number, metadata: boolean): Promise<GASPNode> {
994
- throw new Error('GASP node hydration Not supported!')
1049
+ const output = await this.engine.storage.findOutput(txid, outputIndex)
1050
+
1051
+ if (output === undefined || output === null) {
1052
+ throw new Error('No matching output found!')
1053
+ }
1054
+
1055
+ const tx = Transaction.fromBEEF(output.beef)
1056
+ const rawTx = tx.toHex()
1057
+
1058
+ const node: GASPNode = {
1059
+ rawTx,
1060
+ graphID,
1061
+ outputIndex
1062
+ }
1063
+ if (tx.merklePath !== undefined) {
1064
+ node.proof = tx.merklePath.toHex()
1065
+ }
1066
+
1067
+ return node
995
1068
  }
996
1069
 
997
1070
  /**
@@ -1021,7 +1094,6 @@ export class OverlayGASPStorage implements GASPStorage {
1021
1094
 
1022
1095
  if (admittanceResult.outputsToAdmit.includes(tx.outputIndex)) {
1023
1096
  // The transaction is admissible, no further inputs are needed
1024
- return
1025
1097
  } else {
1026
1098
  // The transaction is not admissible, get inputs needed for further verification
1027
1099
  // TopicManagers should implement a function to identify which inputs are needed.
@@ -1037,20 +1109,9 @@ export class OverlayGASPStorage implements GASPStorage {
1037
1109
  } catch (e) {
1038
1110
  console.error(`An error occurred when identifying needed inputs for transaction: ${parsedTx.id('hex')}.${tx.outputIndex}!`)
1039
1111
  // Cut off the graph in case of an error here.
1040
- return
1041
- }
1042
- } else {
1043
- // In case the topic manager isn't able to stipulate needed inputs, we need to request all inputs as if we had no merkle proof.
1044
- // However, it's dubious that we sometimes don't know — QUESTION: Should we require all topic managers to support this functionality?
1045
- // The alternative to requiring ALL inputs by default is to require NO inputs by default, cutting off the historical graph at this point
1046
- // (e.g. `return undefined`).
1047
- for (const input of parsedTx.inputs) {
1048
- response.requestedInputs[`${input.sourceTXID}.${input.sourceOutputIndex}`] = {
1049
- metadata: false
1050
- }
1051
1112
  }
1052
- return await this.stripAlreadyKnownInputs(response)
1053
1113
  }
1114
+ // By default, if the topic manager isn't able to stipulate needed inputs, only the inputs necessary for SPV are requested.
1054
1115
  }
1055
1116
  // Everything else falls through to returning undefined/void, which will terminate the synchronization at this point.
1056
1117
  }
package/src/GASP.ts ADDED
@@ -0,0 +1,421 @@
1
+ import { Transaction } from '@bsv/sdk'
2
+
3
+ /**
4
+ * Represents the initial request made under the Graph Aware Sync Protocol.
5
+ */
6
+ export type GASPInitialRequest = {
7
+ /** GASP version. Currently 1. */
8
+ version: number
9
+ /** An optional timestamp (UNIX-1970-seconds) of the last time these two parties synced */
10
+ since: number
11
+ }
12
+
13
+ /**
14
+ * Represents the initial response made under the Graph Aware Sync Protocol.
15
+ */
16
+ export type GASPInitialResponse = {
17
+ /** A list of outputs witnessed by the recipient since the initial request's timestamp. If not provided, a complete list of outputs since the beginning of time is returned. Unconfirmed (non-timestamped) UTXOs are always returned. */
18
+ UTXOList: Array<{ txid: string, outputIndex: number }>,
19
+ /** A timestamp from when the responder wants to receive UTXOs in the other direction, back from the requester. */
20
+ since: number
21
+ }
22
+
23
+ /** Represents the subsequent message sent in reply to the initial response. */
24
+ export type GASPInitialReply = {
25
+ /** A list of outputs (excluding outputs received from the Initial Response), and ONLY after the timestamp from the initial response. We don't need to send back things from the initial response, since those were already seen by the counterparty. */
26
+ UTXOList: Array<{ txid: string, outputIndex: number }>,
27
+ }
28
+
29
+ /**
30
+ * Represents an output, its encompassing transaction, and the associated metadata, together with references to inputs and their metadata.
31
+ */
32
+ export type GASPNode = {
33
+ /** The graph ID comprises the currently spendable outpoint that is the subject to the graph to which this node belongs. */
34
+ graphID: string
35
+ /** The Bitcoin transaction in rawTX format. */
36
+ rawTx: string
37
+ /** The index of the output in the transaction. */
38
+ outputIndex: number
39
+ /** A BUMP proof for the transaction, if it is in a block. */
40
+ proof?: string
41
+ /** Metadata associated with the transaction, if it was requested. */
42
+ txMetadata?: string
43
+ /** Metadata associated with the output, if it was requested. */
44
+ outputMetadata?: string
45
+ /** A mapping of transaction inputs, given as an outpoint, to metadata hashes, if metadata was requested. */
46
+ inputs?: Record<string, { hash: string }>
47
+ }
48
+
49
+ /**
50
+ * Denotes which input transactions are requested, and whether metadata needs to be sent.
51
+ */
52
+ export type GASPNodeResponse = {
53
+ requestedInputs: Record<string, { metadata: boolean }>
54
+ }
55
+
56
+ /**
57
+ * Facilitates the finding of UTXOs, determination of needed inputs, temporary graph management, and eventual graph finalization.
58
+ */
59
+ export interface GASPStorage {
60
+ /**
61
+ * Returns an array of transaction outpoints that are currently known to be unspent (given an optional timestamp).
62
+ * Non-confirmed (non-timestamped) outputs should always be returned, regardless of the timestamp.
63
+ * @returns A promise for an array of objects, each containing txid and outputIndex properties.
64
+ */
65
+ findKnownUTXOs: (since: number) => Promise<Array<{ txid: string, outputIndex: number }>>
66
+ /**
67
+ * 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.
68
+ * @param txid The transaction ID for the node to hydrate.
69
+ * @param outputIndex The output index for the node to hydrate.
70
+ * @param metadata Whether transaction and output metadata should be returned.
71
+ * @returns The hydrated GASP node, with or without metadata.
72
+ */
73
+ hydrateGASPNode: (graphID: string, txid: string, outputIndex: number, metadata: boolean) => Promise<GASPNode>
74
+ /**
75
+ * For a given node, returns the inputs needed to complete the graph, including whether updated metadata is requested for those inputs.
76
+ * @param tx The node for which needed inputs should be found.
77
+ * @returns A promise for a mapping of requested input transactions and whether metadata should be provided for each.
78
+ */
79
+ findNeededInputs: (tx: GASPNode) => Promise<GASPNodeResponse | void>
80
+ /**
81
+ * Appends a new node to a temporary graph.
82
+ * @param tx The node to append to this graph.
83
+ * @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.
84
+ * @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.
85
+ */
86
+ appendToGraph: (tx: GASPNode, spentBy?: string) => Promise<void>
87
+ /**
88
+ * 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.
89
+ * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the tip of this graph.
90
+ * @throws If the graph is not well-anchored.
91
+ */
92
+ validateGraphAnchor: (graphID: string) => Promise<void>
93
+ /**
94
+ * Deletes all data associated with a temporary graph that has failed to sync, if the graph exists.
95
+ * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the tip of this graph.
96
+ */
97
+ discardGraph: (graphID: string) => Promise<void>
98
+ /**
99
+ * Finalizes a graph, solidifying the new UTXO and its ancestors so that it will appear in the list of known UTXOs.
100
+ * @param graphID The TXID and output index (in 36-byte format) for the UTXO at the tip of this graph.
101
+ */
102
+ finalizeGraph: (graphID: string) => Promise<void>
103
+ }
104
+
105
+ /**
106
+ * The communications mechanism between a local GASP instance and a foreign GASP instance.
107
+ */
108
+ export interface GASPRemote {
109
+ /** Given an outgoing initial request, send the request to the foreign instance and obtain their initial response. */
110
+ getInitialResponse: (request: GASPInitialRequest) => Promise<GASPInitialResponse>
111
+ /** Given an outgoing initial response, obtain the reply from the foreign instance. */
112
+ getInitialReply?: (response: GASPInitialResponse) => Promise<GASPInitialReply>
113
+ /** Given an outgoing txid, outputIndex and optional metadata, request the associated GASP node from the foreign instance. */
114
+ requestNode: (graphID: string, txid: string, outputIndex: number, metadata: boolean) => Promise<GASPNode>
115
+ /** Given an outgoing node, send the node to the foreign instance and determine which additional inputs (if any) they request in response. */
116
+ submitNode?: (node: GASPNode) => Promise<GASPNodeResponse | void>
117
+ }
118
+
119
+ export class GASPVersionMismatchError extends Error {
120
+ code: 'ERR_GASP_VERSION_MISMATCH'
121
+ currentVersion: number
122
+ foreignVersion: number
123
+
124
+ constructor(message: string, currentVersion: number, foreignVersion: number) {
125
+ super(message)
126
+ this.code = 'ERR_GASP_VERSION_MISMATCH'
127
+ this.currentVersion = currentVersion
128
+ this.foreignVersion = foreignVersion
129
+ }
130
+ }
131
+
132
+ /**
133
+ * Main class implementing the Graph Aware Sync Protocol.
134
+ */
135
+ export class GASP implements GASPRemote {
136
+ version: number
137
+ storage: GASPStorage
138
+ remote: GASPRemote
139
+ lastInteraction: number
140
+ logPrefix: string
141
+ log: boolean
142
+
143
+ /**
144
+ *
145
+ * @param storage The GASP Storage interface to use
146
+ * @param remote The GASP Remote interface to use
147
+ * @param lastInteraction The timestamp when we last interacted with this remote party
148
+ */
149
+ constructor(storage: GASPStorage, remote: GASPRemote, lastInteraction = 0, logPrefix = '[GASP] ', log = false) {
150
+ this.storage = storage
151
+ this.remote = remote
152
+ this.lastInteraction = lastInteraction
153
+ this.version = 1
154
+ this.logPrefix = logPrefix
155
+ this.log = log
156
+ this.validateTimestamp(this.lastInteraction)
157
+ this.logData(`GASP initialized with version: ${this.version}, lastInteraction: ${this.lastInteraction}`)
158
+ }
159
+
160
+ private logData(...data: any): void {
161
+ if (this.log) {
162
+ console.log(this.logPrefix, ...data)
163
+ }
164
+ }
165
+
166
+ private validateTimestamp(timestamp: number): void {
167
+ if (typeof timestamp !== 'number' || isNaN(timestamp) || timestamp < 0 || !Number.isInteger(timestamp)) {
168
+ throw new Error('Invalid timestamp format')
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Computes a 36-byte structure from a transaction ID and output index.
174
+ * @param txid The transaction ID.
175
+ * @param index The output index.
176
+ * @returns A string representing the 36-byte structure.
177
+ */
178
+ private compute36ByteStructure(txid: string, index: number): string {
179
+ const result = `${txid}.${index.toString()}`
180
+ this.logData(`Computed 36-byte structure: ${result} from txid: ${txid}, index: ${index}`)
181
+ return result
182
+ }
183
+
184
+ /**
185
+ * Deconstructs a 36-byte structure into a transaction ID and output index.
186
+ * @param outpoint The 36-byte structure.
187
+ * @returns An object containing the transaction ID and output index.
188
+ */
189
+ private deconstruct36ByteStructure(outpoint: string): { txid: string, outputIndex: number } {
190
+ const [txid, index] = outpoint.split('.')
191
+ const result = {
192
+ txid,
193
+ outputIndex: parseInt(index, 10)
194
+ }
195
+ this.logData(`Deconstructed 36-byte structure: ${outpoint} into txid: ${txid}, outputIndex: ${result.outputIndex}`)
196
+ return result
197
+ }
198
+
199
+ /**
200
+ * Computes the transaction ID for a given transaction.
201
+ * @param tx The transaction string.
202
+ * @returns The computed transaction ID.
203
+ */
204
+ private computeTXID(tx: string): string {
205
+ const txid = Transaction.fromHex(tx).id('hex')
206
+ this.logData(`Computed TXID: ${txid} from transaction: ${tx}`)
207
+ return txid
208
+ }
209
+
210
+ /**
211
+ * Synchronizes the transaction data between the local and remote participants.
212
+ * TODO: Support stipulating upload, download, or bidirectional which should be default.
213
+ */
214
+ async sync(): Promise<void> {
215
+ this.logData(`Starting sync process. Last interaction timestamp: ${this.lastInteraction}`)
216
+ debugger
217
+ const initialRequest = await this.buildInitialRequest(this.lastInteraction)
218
+ const initialResponse = await this.remote.getInitialResponse(initialRequest)
219
+ if (initialResponse.UTXOList.length > 0) {
220
+ const foreignUTXOs = await this.storage.findKnownUTXOs(0)
221
+ await Promise.all(initialResponse.UTXOList
222
+ .filter(x => !foreignUTXOs.some(y => x.txid === y.txid && x.outputIndex === y.outputIndex))
223
+ .map(async UTXO => {
224
+ try {
225
+ this.logData(`Requesting node for UTXO: ${JSON.stringify(UTXO)}`)
226
+ const resolvedNode = await this.remote.requestNode(
227
+ this.compute36ByteStructure(UTXO.txid, UTXO.outputIndex),
228
+ UTXO.txid,
229
+ UTXO.outputIndex,
230
+ true
231
+ )
232
+ this.logData(`Received unspent graph node from remote: ${JSON.stringify(resolvedNode)}`)
233
+ await this.processIncomingNode(resolvedNode)
234
+ await this.completeGraph(resolvedNode.graphID)
235
+ } catch (e) {
236
+ this.logData(`Error with incoming UTXO ${UTXO.txid}.${UTXO.outputIndex}: ${(e as Error).message}`)
237
+ }
238
+ })
239
+ )
240
+ }
241
+
242
+ // const initialReply = await this.getInitialReply(initialResponse)
243
+ // this.logData(`Received initial reply: ${JSON.stringify(initialReply)}`)
244
+
245
+ // if (initialReply.UTXOList.length > 0) {
246
+ // await Promise.all(initialReply.UTXOList.map(async UTXO => {
247
+ // try {
248
+ // this.logData(`Hydrating GASP node for UTXO: ${JSON.stringify(UTXO)}`)
249
+ // const outgoingNode = await this.storage.hydrateGASPNode(
250
+ // this.compute36ByteStructure(UTXO.txid, UTXO.outputIndex),
251
+ // UTXO.txid,
252
+ // UTXO.outputIndex,
253
+ // true
254
+ // )
255
+ // this.logData(`Sending unspent graph node for remote: ${JSON.stringify(outgoingNode)}`)
256
+ // await this.processOutgoingNode(outgoingNode)
257
+ // } catch (e) {
258
+ // this.logData(`Error with outgoing UTXO ${UTXO.txid}.${UTXO.outputIndex}: ${(e as Error).message}`)
259
+ // }
260
+ // }))
261
+ // }
262
+ this.logData('Sync completed!')
263
+ }
264
+
265
+ /**
266
+ * Builds the initial request for the sync process.
267
+ * @returns A promise for the initial request object.
268
+ */
269
+ async buildInitialRequest(since: number): Promise<GASPInitialRequest> {
270
+ const request = {
271
+ version: this.version,
272
+ since
273
+ }
274
+ this.logData(`Built initial request: ${JSON.stringify(request)}`)
275
+ return request
276
+ }
277
+
278
+ /**
279
+ * Builds the initial response based on the received request.
280
+ * @param request The initial request object.
281
+ * @returns A promise for an initial response
282
+ */
283
+ async getInitialResponse(request: GASPInitialRequest): Promise<GASPInitialResponse> {
284
+ this.logData(`Received initial request: ${JSON.stringify(request)}`)
285
+ if (request.version !== this.version) {
286
+ const error = new GASPVersionMismatchError(
287
+ `GASP version mismatch. Current version: ${this.version}, foreign version: ${request.version}`,
288
+ this.version,
289
+ request.version
290
+ )
291
+ console.error(`GASP version mismatch error: ${error.message}`)
292
+ throw error
293
+ }
294
+ this.validateTimestamp(request.since)
295
+ const response = {
296
+ since: this.lastInteraction,
297
+ UTXOList: await this.storage.findKnownUTXOs(request.since)
298
+ }
299
+ this.logData(`Built initial response: ${JSON.stringify(response)}`)
300
+ return response
301
+ }
302
+
303
+ /**
304
+ * Builds the initial reply based on the received response.
305
+ * @param response The initial response object.
306
+ * @returns A promise for an initial reply
307
+ */
308
+ async getInitialReply(response: GASPInitialResponse): Promise<GASPInitialReply> {
309
+ this.logData(`Received initial response: ${JSON.stringify(response)}`)
310
+ const knownUTXOs = await this.storage.findKnownUTXOs(response.since)
311
+ const filteredUTXOs = knownUTXOs.filter(x => !response.UTXOList.some(y => y.txid === x.txid && y.outputIndex === x.outputIndex))
312
+ const reply = {
313
+ UTXOList: filteredUTXOs
314
+ }
315
+ this.logData(`Built initial reply: ${JSON.stringify(reply)}`)
316
+ return reply
317
+ }
318
+
319
+ /**
320
+ * Provides a requested node to a foreign instance who requested it.
321
+ */
322
+ async requestNode(graphID: string, txid: string, outputIndex: number, metadata: boolean): Promise<GASPNode> {
323
+ this.logData(`Remote is requesting node with graphID: ${graphID}, txid: ${txid}, outputIndex: ${outputIndex}, metadata: ${metadata}`)
324
+ const node = await this.storage.hydrateGASPNode(graphID, txid, outputIndex, metadata)
325
+ this.logData(`Returning node: ${JSON.stringify(node)}`)
326
+ return node
327
+ }
328
+
329
+ /**
330
+ * Provides a set of inputs we care about after processing a new incoming node.
331
+ * Also finalizes or discards a graph if no additional data is requested from the foreign instance.
332
+ */
333
+ async submitNode(node: GASPNode): Promise<GASPNodeResponse | void> {
334
+ this.logData(`Remote party is submitting node: ${JSON.stringify(node)}`)
335
+ await this.storage.appendToGraph(node)
336
+ const requestedInputs = await this.storage.findNeededInputs(node)
337
+ this.logData(`Requested inputs: ${JSON.stringify(requestedInputs)}`)
338
+ if (!requestedInputs) {
339
+ await this.completeGraph(node.graphID)
340
+ }
341
+ return requestedInputs
342
+ }
343
+
344
+ /**
345
+ * Handles the completion of a newly-synced graph
346
+ * @param {string} graphID The ID of the newly-synced graph
347
+ */
348
+ async completeGraph(graphID: string): Promise<void> {
349
+ this.logData(`Completing newly-synced graph: ${graphID}`)
350
+ try {
351
+ await this.storage.validateGraphAnchor(graphID)
352
+ this.logData(`Graph validated for node: ${graphID}`)
353
+ await this.storage.finalizeGraph(graphID)
354
+ this.logData(`Graph finalized for node: ${graphID}`)
355
+ } catch (e) {
356
+ this.logData(`Error validating graph: ${(e as Error).message}. Discarding graph for node: ${graphID}`)
357
+ await this.storage.discardGraph(graphID)
358
+ }
359
+ }
360
+
361
+ /**
362
+ * Processes an incoming node from the remote participant.
363
+ * @param node The incoming GASP node.
364
+ * @param spentBy The 36-byte structure of the node that spent this one, if applicable.
365
+ */
366
+ private async processIncomingNode(node: GASPNode, spentBy?: string, seenNodes = new Set()): Promise<void> {
367
+ const nodeId = `${this.computeTXID(node.rawTx)}.${node.outputIndex}`
368
+ this.logData(`Processing incoming node: ${JSON.stringify(node)}, spentBy: ${spentBy}`)
369
+ if (seenNodes.has(nodeId)) {
370
+ this.logData(`Node ${nodeId} already processed, skipping.`)
371
+ return // Prevent infinite recursion
372
+ }
373
+ seenNodes.add(nodeId)
374
+ await this.storage.appendToGraph(node, spentBy)
375
+ const neededInputs = await this.storage.findNeededInputs(node)
376
+ this.logData(`Needed inputs for node ${nodeId}: ${JSON.stringify(neededInputs)}`)
377
+ if (neededInputs) {
378
+ await Promise.all(Object.entries(neededInputs.requestedInputs).map(async ([outpoint, { metadata }]) => {
379
+ const { txid, outputIndex } = this.deconstruct36ByteStructure(outpoint)
380
+ this.logData(`Requesting new node for txid: ${txid}, outputIndex: ${outputIndex}, metadata: ${metadata}`)
381
+ const newNode = await this.remote.requestNode(node.graphID, txid, outputIndex, metadata)
382
+ this.logData(`Received new node: ${JSON.stringify(newNode)}`)
383
+ await this.processIncomingNode(newNode, this.compute36ByteStructure(this.computeTXID(node.rawTx), node.outputIndex), seenNodes)
384
+ }))
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Processes an outgoing node to the remote participant.
390
+ * @param node The outgoing GASP node.
391
+ */
392
+ private async processOutgoingNode(node: GASPNode, seenNodes = new Set()): Promise<void> {
393
+ const nodeId = `${this.computeTXID(node.rawTx)}.${node.outputIndex}`
394
+ this.logData(`Processing outgoing node: ${JSON.stringify(node)}`)
395
+ if (seenNodes.has(nodeId)) {
396
+ this.logData(`Node ${nodeId} already processed, skipping.`)
397
+ return // Prevent infinite recursion
398
+ }
399
+ seenNodes.add(nodeId)
400
+ if (this.remote.submitNode === undefined) {
401
+ throw new Error('Remote does not support GASP node submission!')
402
+ }
403
+ const response = await this.remote.submitNode(node)
404
+ this.logData(`Received response for submitted node: ${JSON.stringify(response)}`)
405
+ if (response) {
406
+ await Promise.all(Object.entries(response.requestedInputs).map(async ([outpoint, { metadata }]) => {
407
+ const { txid, outputIndex } = this.deconstruct36ByteStructure(outpoint)
408
+ try {
409
+ this.logData(`Hydrating node for txid: ${txid}, outputIndex: ${outputIndex}, metadata: ${metadata}`)
410
+ const hydratedNode = await this.storage.hydrateGASPNode(node.graphID, txid, outputIndex, metadata)
411
+ this.logData(`Hydrated node: ${JSON.stringify(hydratedNode)}`)
412
+ await this.processOutgoingNode(hydratedNode, seenNodes)
413
+ } catch (e) {
414
+ this.logData(`Error hydrating node: ${(e as Error).message}`)
415
+ // If we can't send the outgoing node, we just stop. The remote won't validate the anchor, and their temporary graph will be discarded.
416
+ return
417
+ }
418
+ }))
419
+ }
420
+ }
421
+ }