@electrum-cash/network 3.2.0-r1 → 3.3.0-development.6103536979

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/dist/index.mjs ADDED
@@ -0,0 +1,1611 @@
1
+ import {EventEmitter as $4QiMX$EventEmitter} from "events";
2
+ import {Mutex as $4QiMX$Mutex} from "async-mutex";
3
+ import $4QiMX$debug from "debug";
4
+ import {parse as $4QiMX$parse, parseNumberAndBigInt as $4QiMX$parseNumberAndBigInt, stringify as $4QiMX$stringify} from "lossless-json";
5
+ import {connect as $4QiMX$connect, TLSSocket as $4QiMX$TLSSocket} from "tls";
6
+ import {isIP as $4QiMX$isIP, connect as $4QiMX$connect1} from "net";
7
+ import {WebSocket as $4QiMX$WebSocket} from "@monsterbitar/isomorphic-ws";
8
+
9
+
10
+ function $parcel$export(e, n, v, s) {
11
+ Object.defineProperty(e, n, {get: v, set: s, enumerable: true, configurable: true});
12
+ }
13
+
14
+ // Create the debug logs.
15
+ const $ef5ba40c8abe5a13$var$debug = {
16
+ client: (0, $4QiMX$debug)("electrum-cash:client "),
17
+ cluster: (0, $4QiMX$debug)("electrum-cash:cluster"),
18
+ errors: (0, $4QiMX$debug)("electrum-cash:error "),
19
+ warning: (0, $4QiMX$debug)("electrum-cash:warning"),
20
+ network: (0, $4QiMX$debug)("electrum-cash:network"),
21
+ ping: (0, $4QiMX$debug)("electrum-cash:pulses ")
22
+ };
23
+ // Set log colors.
24
+ $ef5ba40c8abe5a13$var$debug.client.color = "2";
25
+ $ef5ba40c8abe5a13$var$debug.cluster.color = "3";
26
+ $ef5ba40c8abe5a13$var$debug.errors.color = "9";
27
+ $ef5ba40c8abe5a13$var$debug.warning.color = "13";
28
+ $ef5ba40c8abe5a13$var$debug.network.color = "4";
29
+ $ef5ba40c8abe5a13$var$debug.ping.color = "8";
30
+ var // Export the logs.
31
+ $ef5ba40c8abe5a13$export$2e2bcd8739ae039 = $ef5ba40c8abe5a13$var$debug;
32
+
33
+
34
+
35
+ /**
36
+ * Grouping of utilities that simplifies implementation of the Electrum protocol.
37
+ *
38
+ * @ignore
39
+ */ class $c78f59d21170b7a6$var$ElectrumProtocol {
40
+ /**
41
+ * Helper function that builds an Electrum request object.
42
+ *
43
+ * @param {string} method method to call.
44
+ * @param {array} parameters method parameters for the call.
45
+ * @param {string} requestId unique string or number referencing this request.
46
+ *
47
+ * @returns a properly formatted Electrum request string.
48
+ */ static buildRequestObject(method, parameters, requestId) {
49
+ // Return the formatted request object.
50
+ // NOTE: Electrum either uses JsonRPC strictly or loosely.
51
+ // If we specify protocol identifier without being 100% compliant, we risk being disconnected/blacklisted.
52
+ // For this reason, we omit the protocol identifier to avoid issues.
53
+ return JSON.stringify({
54
+ method: method,
55
+ params: parameters,
56
+ id: requestId
57
+ });
58
+ }
59
+ /**
60
+ * Constant used to verify if a provided string is a valid version number.
61
+ *
62
+ * @returns a regular expression that matches valid version numbers.
63
+ */ static get versionRegexp() {
64
+ return /^\d+(\.\d+)+$/;
65
+ }
66
+ /**
67
+ * Constant used to separate statements/messages in a stream of data.
68
+ *
69
+ * @returns the delimiter used by Electrum to separate statements.
70
+ */ static get statementDelimiter() {
71
+ return "\n";
72
+ }
73
+ }
74
+ var // export the protocol.
75
+ $c78f59d21170b7a6$export$2e2bcd8739ae039 = $c78f59d21170b7a6$var$ElectrumProtocol;
76
+
77
+
78
+ var $a192ea5a4eec42d4$exports = {};
79
+
80
+ $parcel$export($a192ea5a4eec42d4$exports, "isVersionRejected", () => $a192ea5a4eec42d4$export$e1f38ab2b4ebdde6);
81
+ $parcel$export($a192ea5a4eec42d4$exports, "isVersionNegotiated", () => $a192ea5a4eec42d4$export$9598f0c76aa41d73);
82
+ const $a192ea5a4eec42d4$export$e1f38ab2b4ebdde6 = function(object) {
83
+ return "error" in object;
84
+ };
85
+ const $a192ea5a4eec42d4$export$9598f0c76aa41d73 = function(object) {
86
+ return "software" in object && "protocol" in object;
87
+ };
88
+
89
+
90
+ var $5abc8fb342687c03$exports = {};
91
+
92
+ $parcel$export($5abc8fb342687c03$exports, "ElectrumTransport", () => $5abc8fb342687c03$export$d048df559e6d3842);
93
+ $parcel$export($5abc8fb342687c03$exports, "DefaultParameters", () => $5abc8fb342687c03$export$f019be48b3aacb1a);
94
+ var $a58372b18a18806e$exports = {};
95
+
96
+ $parcel$export($a58372b18a18806e$exports, "ClusterOrder", () => $a58372b18a18806e$export$161fe3707f756bf9);
97
+ $parcel$export($a58372b18a18806e$exports, "ClusterDistribution", () => $a58372b18a18806e$export$436a960acc41e848);
98
+ $parcel$export($a58372b18a18806e$exports, "ClusterStatus", () => $a58372b18a18806e$export$c66b56bc0ff967ca);
99
+ $parcel$export($a58372b18a18806e$exports, "ClientState", () => $a58372b18a18806e$export$c4f81c6d30ca200f);
100
+ $parcel$export($a58372b18a18806e$exports, "ConnectionStatus", () => $a58372b18a18806e$export$7516420eb880ab68);
101
+ // Disable indent rule for this file because it is broken (https://github.com/typescript-eslint/typescript-eslint/issues/1824)
102
+ /* eslint-disable @typescript-eslint/indent */ /**
103
+ * Enum that denotes the ordering to use in an ElectrumCluster.
104
+ * @enum {number}
105
+ * @property {0} RANDOM Send requests to randomly selected servers in the cluster.
106
+ * @property {1} PRIORITY Send requests to servers in the cluster in the order they were added.
107
+ */ var $a58372b18a18806e$export$161fe3707f756bf9;
108
+ (function(ClusterOrder) {
109
+ ClusterOrder[ClusterOrder["RANDOM"] = 0] = "RANDOM";
110
+ ClusterOrder[ClusterOrder["PRIORITY"] = 1] = "PRIORITY";
111
+ })($a58372b18a18806e$export$161fe3707f756bf9 || ($a58372b18a18806e$export$161fe3707f756bf9 = {}));
112
+ var $a58372b18a18806e$export$436a960acc41e848;
113
+ (function(ClusterDistribution) {
114
+ ClusterDistribution[ClusterDistribution["ALL"] = 0] = "ALL";
115
+ })($a58372b18a18806e$export$436a960acc41e848 || ($a58372b18a18806e$export$436a960acc41e848 = {}));
116
+ var $a58372b18a18806e$export$c66b56bc0ff967ca;
117
+ (function(ClusterStatus) {
118
+ ClusterStatus[ClusterStatus["DISABLED"] = 0] = "DISABLED";
119
+ ClusterStatus[ClusterStatus["DEGRADED"] = 1] = "DEGRADED";
120
+ ClusterStatus[ClusterStatus["READY"] = 2] = "READY";
121
+ })($a58372b18a18806e$export$c66b56bc0ff967ca || ($a58372b18a18806e$export$c66b56bc0ff967ca = {}));
122
+ var $a58372b18a18806e$export$c4f81c6d30ca200f;
123
+ (function(ClientState) {
124
+ ClientState[ClientState["UNAVAILABLE"] = 0] = "UNAVAILABLE";
125
+ ClientState[ClientState["AVAILABLE"] = 1] = "AVAILABLE";
126
+ })($a58372b18a18806e$export$c4f81c6d30ca200f || ($a58372b18a18806e$export$c4f81c6d30ca200f = {}));
127
+ var $a58372b18a18806e$export$7516420eb880ab68;
128
+ (function(ConnectionStatus) {
129
+ ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 0] = "DISCONNECTED";
130
+ ConnectionStatus[ConnectionStatus["CONNECTED"] = 1] = "CONNECTED";
131
+ ConnectionStatus[ConnectionStatus["DISCONNECTING"] = 2] = "DISCONNECTING";
132
+ ConnectionStatus[ConnectionStatus["CONNECTING"] = 3] = "CONNECTING";
133
+ ConnectionStatus[ConnectionStatus["RECONNECTING"] = 4] = "RECONNECTING";
134
+ })($a58372b18a18806e$export$7516420eb880ab68 || ($a58372b18a18806e$export$7516420eb880ab68 = {}));
135
+
136
+
137
+ const $5abc8fb342687c03$export$d048df559e6d3842 = {
138
+ TCP: {
139
+ Port: 50001,
140
+ Scheme: "tcp"
141
+ },
142
+ TCP_TLS: {
143
+ Port: 50002,
144
+ Scheme: "tcp_tls"
145
+ },
146
+ WS: {
147
+ Port: 50003,
148
+ Scheme: "ws"
149
+ },
150
+ WSS: {
151
+ Port: 50004,
152
+ Scheme: "wss"
153
+ }
154
+ };
155
+ const $5abc8fb342687c03$export$f019be48b3aacb1a = {
156
+ // Port number for TCP TLS connections
157
+ PORT: $5abc8fb342687c03$export$d048df559e6d3842.TCP_TLS.Port,
158
+ // Transport to connect to the Electrum server
159
+ TRANSPORT_SCHEME: $5abc8fb342687c03$export$d048df559e6d3842.TCP_TLS.Scheme,
160
+ // How long to wait before attempting to reconnect, in milliseconds.
161
+ RECONNECT: 5000,
162
+ // How long to wait for network operations before following up, in milliseconds.
163
+ TIMEOUT: 30000,
164
+ // Time between ping messages, in milliseconds. Pinging keeps the connection alive.
165
+ // The reason for pinging this frequently is to detect connection problems early.
166
+ PING_INTERVAL: 1000,
167
+ // How many servers are required before we trust information provided.
168
+ CLUSTER_CONFIDENCE: 1,
169
+ // How many servers we send requests to.
170
+ CLUSTER_DISTRIBUTION: (0, $a58372b18a18806e$export$436a960acc41e848).ALL,
171
+ // What order we select servers to send requests to.
172
+ CLUSTER_ORDER: (0, $a58372b18a18806e$export$161fe3707f756bf9).RANDOM,
173
+ // If we use BigInt for numbers in json when parsing and returning json response from the server.
174
+ USE_BIG_INT: false
175
+ };
176
+
177
+
178
+
179
+
180
+
181
+
182
+
183
+
184
+
185
+ /**
186
+ * Isomorphic Socket interface supporting TCP sockets and WebSockets (Node and browser).
187
+ * The interface is a subset of the TLSSocket interface with some slight modifications.
188
+ * It can be expanded when more socket functionality is needed in the rest of the
189
+ * electrum-cash code. Changes from the TLSSocket interface (besides it being a subset):
190
+ * - Event 'close' -> 'disconnect'
191
+ * - New function socket.disconnect()
192
+ *
193
+ * @ignore
194
+ */ class $ea64e414b68fe23b$var$ElectrumSocket extends (0, $4QiMX$EventEmitter) {
195
+ /**
196
+ * Connect to host:port using the specified transport
197
+ *
198
+ * @param {string} host Fully qualified domain name or IP address of the host
199
+ * @param {number} port Network port for the host to connect to
200
+ * @param {TransportScheme} scheme Transport scheme to use
201
+ * @param {number} timeout If no connection is established after `timeout` ms, the connection is terminated
202
+ *
203
+ * @throws {Error} if an incorrect transport scheme is specified
204
+ */ connect(host, port, scheme, timeout) {
205
+ // Check that no existing socket exists before initiating a new connection.
206
+ if (this.tcpSocket || this.webSocket) throw new Error("Cannot initiate a new socket connection when an existing connection exists");
207
+ // Set a timer to force disconnect after `timeout` seconds
208
+ this.timers.disconnect = setTimeout(()=>this.disconnectOnTimeout(host, port, timeout), timeout);
209
+ // Remove the timer if a connection is successfully established
210
+ this.once("connect", this.clearDisconnectTimerOnTimeout);
211
+ // Define how to refer to the connection scheme in debug output.
212
+ const socketTypes = {
213
+ [(0, $5abc8fb342687c03$export$d048df559e6d3842).TCP.Scheme]: "a TCP Socket",
214
+ [(0, $5abc8fb342687c03$export$d048df559e6d3842).TCP_TLS.Scheme]: "an encrypted TCP socket",
215
+ [(0, $5abc8fb342687c03$export$d048df559e6d3842).WS.Scheme]: "a WebSocket",
216
+ [(0, $5abc8fb342687c03$export$d048df559e6d3842).WSS.Scheme]: "an encrypted WebSocket"
217
+ };
218
+ // Log that we are trying to establish a connection.
219
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Initiating ${socketTypes[scheme]} connection to '${host}:${port}'.`);
220
+ if (scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).TCP.Scheme || scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).TCP_TLS.Scheme) {
221
+ if (scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).TCP_TLS.Scheme) {
222
+ // Initialize connection options.
223
+ const connectionOptions = {
224
+ rejectUnauthorized: false
225
+ };
226
+ // If the hostname is not an IP address..
227
+ if (!$4QiMX$isIP(host)) // Set the servername option which enables support for SNI.
228
+ // NOTE: SNI enables a server that hosts multiple domains to provide the appropriate TLS certificate.
229
+ connectionOptions.serverName = host;
230
+ // Initialize this.tcpSocket (allowing self-signed certificates).
231
+ this.tcpSocket = $4QiMX$connect(port, host, connectionOptions);
232
+ // Add a 'secureConnect' listener that checks the authorization status of
233
+ // the socket, and logs a warning when it uses a self signed certificate.
234
+ this.tcpSocket.once("secureConnect", ()=>{
235
+ // Cannot happen, since this event callback *only* exists on TLSSocket
236
+ if (!(this.tcpSocket instanceof $4QiMX$TLSSocket)) return;
237
+ // Force cast authorizationError from Error to string (through unknown)
238
+ // because it is incorrectly typed as an Error
239
+ const authorizationError = this.tcpSocket.authorizationError;
240
+ if (authorizationError === "DEPTH_ZERO_SELF_SIGNED_CERT") (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).warning(`Connection to ${host}:${port} uses a self-signed certificate`);
241
+ });
242
+ // Trigger successful connection events.
243
+ this.tcpSocket.on("secureConnect", this.onConnect.bind(this, socketTypes[scheme], host, port));
244
+ } else {
245
+ // Initialize this.tcpSocket.
246
+ this.tcpSocket = $4QiMX$connect1({
247
+ host: host,
248
+ port: port
249
+ });
250
+ // Trigger successful connection events.
251
+ this.tcpSocket.on("connect", this.onConnect.bind(this, socketTypes[scheme], host, port));
252
+ }
253
+ // Configure encoding.
254
+ this.tcpSocket.setEncoding("utf8");
255
+ // Enable persistent connections with an initial delay of 0.
256
+ this.tcpSocket.setKeepAlive(true, 0);
257
+ // Disable buffering of outgoing data.
258
+ this.tcpSocket.setNoDelay(true);
259
+ // Forward the encountered errors.
260
+ this.tcpSocket.on("error", this.eventForwarders.tcpError);
261
+ } else if (scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).WS.Scheme || scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).WSS.Scheme) {
262
+ if (scheme === (0, $5abc8fb342687c03$export$d048df559e6d3842).WSS.Scheme) // Initialize this.webSocket (rejecting self-signed certificates).
263
+ // We reject self-signed certificates to match functionality of browsers.
264
+ this.webSocket = new (0, $4QiMX$WebSocket)(`wss://${host}:${port}`);
265
+ else // Initialize this.webSocket.
266
+ this.webSocket = new (0, $4QiMX$WebSocket)(`ws://${host}:${port}`);
267
+ // Trigger successful connection events.
268
+ this.webSocket.addEventListener("open", this.onConnect.bind(this, socketTypes[scheme], host, port));
269
+ // Forward the encountered errors.
270
+ this.webSocket.addEventListener("error", this.eventForwarders.wsError);
271
+ } else // Throw an error if an incorrect transport is specified
272
+ throw new Error("Incorrect transport specified");
273
+ }
274
+ /**
275
+ * Sets up forwarding of events related to the connection.
276
+ *
277
+ * @param {string} connectionType Name of the connection/transport type, used for logging.
278
+ * @param {string} host Fully qualified domain name or IP address of the host
279
+ * @param {number} port Network port for the host to connect to
280
+ */ onConnect(connectionType, host, port) {
281
+ // If the onConnect function has already run, do not execute it again.
282
+ if (this.onConnectHasRun) return;
283
+ // Log that the connection has been established.
284
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Established ${connectionType} connection with '${host}:${port}'.`);
285
+ if (typeof this.tcpSocket !== "undefined") {
286
+ // Forward the socket events
287
+ this.tcpSocket.addListener("close", this.eventForwarders.disconnect);
288
+ this.tcpSocket.addListener("data", this.eventForwarders.tcpData);
289
+ } else if (typeof this.webSocket !== "undefined") {
290
+ // Forward the socket events
291
+ this.webSocket.addEventListener("close", this.eventForwarders.disconnect);
292
+ this.webSocket.addEventListener("message", this.eventForwarders.wsData);
293
+ }
294
+ // Indicate that the onConnect function has run.
295
+ this.onConnectHasRun = true;
296
+ // Emit the connect event.
297
+ this.emit("connect");
298
+ }
299
+ /**
300
+ * Clears the disconnect timer if it is still active.
301
+ */ clearDisconnectTimerOnTimeout() {
302
+ // Clear the retry timer if it is still active.
303
+ if (this.timers.disconnect) clearTimeout(this.timers.disconnect);
304
+ }
305
+ /**
306
+ * Forcibly terminate the connection.
307
+ *
308
+ * @throws {Error} if no connection was found
309
+ */ disconnect() {
310
+ // Clear the disconnect timer so that the socket does not try to disconnect again later.
311
+ this.clearDisconnectTimerOnTimeout();
312
+ // Handle disconnect based differently depending on socket type.
313
+ if (this.tcpSocket) {
314
+ // Remove all event forwarders.
315
+ this.tcpSocket.removeListener("close", this.eventForwarders.disconnect);
316
+ this.tcpSocket.removeListener("data", this.eventForwarders.tcpData);
317
+ this.tcpSocket.removeListener("error", this.eventForwarders.tcpError);
318
+ // Terminate the connection.
319
+ this.tcpSocket.destroy();
320
+ // Remove the stored socket.
321
+ this.tcpSocket = undefined;
322
+ } else if (this.webSocket) try {
323
+ // Remove all event forwarders.
324
+ this.webSocket.removeEventListener("close", this.eventForwarders.disconnect);
325
+ this.webSocket.removeEventListener("message", this.eventForwarders.wsData);
326
+ this.webSocket.removeEventListener("error", this.eventForwarders.wsError);
327
+ // Gracefully terminate the connection.
328
+ this.webSocket.close();
329
+ } catch (ignored) {
330
+ // close() will throw an error if the connection has not been established yet.
331
+ // We ignore this error, since no similar error gets thrown in the TLS Socket.
332
+ } finally{
333
+ // Remove the stored socket regardless of any thrown errors.
334
+ this.webSocket = undefined;
335
+ }
336
+ // Indicate that the onConnect function has not run and it has to be run again.
337
+ this.onConnectHasRun = false;
338
+ // Emit a disconnect event
339
+ this.emit("disconnect");
340
+ }
341
+ /**
342
+ * Write data to the socket
343
+ *
344
+ * @param {Uint8Array | string} data Data to be written to the socket
345
+ * @param {function} callback Callback function to be called when the write has completed
346
+ *
347
+ * @throws {Error} if no connection was found
348
+ * @returns true if the message was fully flushed to the socket, false if part of the message
349
+ * is queued in the user memory
350
+ */ write(data, callback) {
351
+ if (this.tcpSocket) // Write data to the TLS Socket and return the status indicating whether the
352
+ // full message was flushed to the socket
353
+ return this.tcpSocket.write(data, callback);
354
+ if (this.webSocket) {
355
+ // Write data to the WebSocket
356
+ this.webSocket.send(data, callback);
357
+ // WebSockets always fit everything in a single request, so we return true
358
+ return true;
359
+ }
360
+ // Throw an error if no active connection is found
361
+ throw new Error("Cannot write to socket when there is no active connection");
362
+ }
363
+ /**
364
+ * Force a disconnection if no connection is established after `timeout` milliseconds.
365
+ *
366
+ * @param {string} host Host of the connection that timed out
367
+ * @param {number} port Port of the connection that timed out
368
+ * @param {number} timeout Elapsed milliseconds
369
+ */ disconnectOnTimeout(host, port, timeout) {
370
+ // Remove the connect listener.
371
+ this.removeListener("connect", this.clearDisconnectTimerOnTimeout);
372
+ // Create a new timeout error.
373
+ const timeoutError = {
374
+ code: "ETIMEDOUT",
375
+ message: `Connection to '${host}:${port}' timed out after ${timeout} milliseconds`
376
+ };
377
+ // Emit an error event so that connect is rejected upstream.
378
+ this.emit("error", timeoutError);
379
+ // Forcibly disconnect to clean up the connection on timeout
380
+ this.disconnect();
381
+ }
382
+ constructor(...args){
383
+ super(...args);
384
+ // Declare timers for keep-alive pings and reconnection
385
+ this.timers = {};
386
+ // Initialize boolean that indicates whether the onConnect function has run (initialize to false).
387
+ this.onConnectHasRun = false;
388
+ // Initialize event forwarding functions.
389
+ this.eventForwarders = {
390
+ disconnect: ()=>this.emit("disconnect"),
391
+ tcpData: (data)=>this.emit("data", data),
392
+ wsData: (event)=>this.emit("data", `${event.data}\n`),
393
+ tcpError: (err)=>this.emit("error", err),
394
+ wsError: (event)=>this.emit("error", event.error)
395
+ };
396
+ }
397
+ }
398
+ var // export the socket.
399
+ $ea64e414b68fe23b$export$2e2bcd8739ae039 = $ea64e414b68fe23b$var$ElectrumSocket;
400
+
401
+
402
+
403
+
404
+ /**
405
+ * Wrapper around TLS/WSS sockets that gracefully separates a network stream into Electrum protocol messages.
406
+ *
407
+ * @ignore
408
+ */ class $1326c18f93f95fee$var$ElectrumConnection extends (0, $4QiMX$EventEmitter) {
409
+ /**
410
+ * Sets up network configuration for an Electrum client connection.
411
+ *
412
+ * @param {string} application your application name, used to identify to the electrum host.
413
+ * @param {string} version protocol version to use with the host.
414
+ * @param {string} host fully qualified domain name or IP number of the host.
415
+ * @param {number} port the network port of the host.
416
+ * @param {TransportScheme} scheme the transport scheme to use for connection
417
+ * @param {number} timeout how long network delays we will wait for before taking action, in milliseconds.
418
+ * @param {number} pingInterval the time between sending pings to the electrum host, in milliseconds.
419
+ * @param {number} reconnectInterval the time between reconnection attempts to the electrum host, in milliseconds.
420
+ * @param {boolean} useBigInt whether to use bigint for numbers in json response.
421
+ *
422
+ * @throws {Error} if `version` is not a valid version string.
423
+ */ constructor(application, version, host, port = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PORT, scheme = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TRANSPORT_SCHEME, timeout = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TIMEOUT, pingInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PING_INTERVAL, reconnectInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).RECONNECT, useBigInt = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).USE_BIG_INT){
424
+ // Initialize the event emitter.
425
+ super();
426
+ this.application = application;
427
+ this.version = version;
428
+ this.host = host;
429
+ this.port = port;
430
+ this.scheme = scheme;
431
+ this.timeout = timeout;
432
+ this.pingInterval = pingInterval;
433
+ this.reconnectInterval = reconnectInterval;
434
+ this.useBigInt = useBigInt;
435
+ this.// Declare timers for keep-alive pings and reconnection
436
+ timers = {};
437
+ this.// Initialize an empty array of connection verification timers.
438
+ // eslint-disable-next-line no-undef
439
+ verifications = [];
440
+ this.// Initialize the connected flag to false to indicate that there is no connection
441
+ status = (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED;
442
+ this.// Initialize messageBuffer to an empty string
443
+ messageBuffer = "";
444
+ // Check if the provided version is a valid version number.
445
+ if (!(0, $c78f59d21170b7a6$export$2e2bcd8739ae039).versionRegexp.test(version)) // Throw an error since the version number was not valid.
446
+ throw new Error(`Provided version string (${version}) is not a valid protocol version number.`);
447
+ // Create an initial network socket.
448
+ this.createSocket();
449
+ // Handle visibility changes when run in a browser environment.
450
+ if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.handleVisibilityChange.bind(this));
451
+ }
452
+ /**
453
+ * Returns a string for the host identifier for usage in debug messages.
454
+ */ get hostIdentifier() {
455
+ return `${this.host}:${this.port}`;
456
+ }
457
+ /**
458
+ * Create and configures a fresh socket and attaches all relevant listeners.
459
+ */ createSocket() {
460
+ // Initialize a new ElectrumSocket
461
+ this.socket = new (0, $ea64e414b68fe23b$export$2e2bcd8739ae039)();
462
+ // Set up handlers for connection and disconnection.
463
+ this.socket.on("connect", this.onSocketConnect.bind(this));
464
+ this.socket.on("disconnect", this.onSocketDisconnect.bind(this));
465
+ // Set up handler for incoming data.
466
+ this.socket.on("data", this.parseMessageChunk.bind(this));
467
+ }
468
+ /**
469
+ * Shuts down and destroys the current socket.
470
+ */ destroySocket() {
471
+ // Close the socket connection and destroy the socket.
472
+ this.socket.disconnect();
473
+ }
474
+ /**
475
+ * Assembles incoming data into statements and hands them off to the message parser.
476
+ *
477
+ * @param {string} data data to append to the current message buffer, as a string.
478
+ *
479
+ * @throws {SyntaxError} if the passed statement parts are not valid JSON.
480
+ */ parseMessageChunk(data) {
481
+ // Update the timestamp for when we last received data.
482
+ this.lastReceivedTimestamp = Date.now();
483
+ // Clear and remove all verification timers.
484
+ this.verifications.forEach((timer)=>clearTimeout(timer));
485
+ this.verifications.length = 0;
486
+ // Add the message to the current message buffer.
487
+ this.messageBuffer += data;
488
+ // Check if the new message buffer contains the statement delimiter.
489
+ while(this.messageBuffer.includes((0, $c78f59d21170b7a6$export$2e2bcd8739ae039).statementDelimiter)){
490
+ // Split message buffer into statements.
491
+ const statementParts = this.messageBuffer.split((0, $c78f59d21170b7a6$export$2e2bcd8739ae039).statementDelimiter);
492
+ // For as long as we still have statements to parse..
493
+ while(statementParts.length > 1){
494
+ // Move the first statement to its own variable.
495
+ const currentStatementList = String(statementParts.shift());
496
+ // Parse the statement into an object or list of objects.
497
+ let statementList = (0, $4QiMX$parse)(currentStatementList, null, this.useBigInt ? (0, $4QiMX$parseNumberAndBigInt) : parseFloat);
498
+ // Wrap the statement in an array if it is not already a batched statement list.
499
+ if (!Array.isArray(statementList)) statementList = [
500
+ statementList
501
+ ];
502
+ // For as long as there is statements in the result set..
503
+ while(statementList.length > 0){
504
+ // Move the first statement from the batch to its own variable.
505
+ const currentStatement = statementList.shift();
506
+ // If the current statement is a version negotiation response..
507
+ if (currentStatement.id === "versionNegotiation") {
508
+ if (currentStatement.error) // Then emit a failed version negotiation response signal.
509
+ this.emit("version", {
510
+ error: currentStatement.error
511
+ });
512
+ else // Emit a successful version negotiation response signal.
513
+ this.emit("version", {
514
+ software: currentStatement.result[0],
515
+ protocol: currentStatement.result[1]
516
+ });
517
+ continue;
518
+ }
519
+ // If the current statement is a keep-alive response..
520
+ if (currentStatement.id === "keepAlive") continue;
521
+ // Emit the statements for handling higher up in the stack.
522
+ this.emit("statement", currentStatement);
523
+ }
524
+ }
525
+ // Store the remaining statement as the current message buffer.
526
+ this.messageBuffer = statementParts.shift() || "";
527
+ }
528
+ }
529
+ /**
530
+ * Sends a keep-alive message to the host.
531
+ *
532
+ * @returns true if the ping message was fully flushed to the socket, false if
533
+ * part of the message is queued in the user memory
534
+ */ ping() {
535
+ // Write a log message.
536
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).ping(`Sending keep-alive ping to '${this.hostIdentifier}'`);
537
+ // Craft a keep-alive message.
538
+ const message = (0, $c78f59d21170b7a6$export$2e2bcd8739ae039).buildRequestObject("server.ping", [], "keepAlive");
539
+ // Send the keep-alive message.
540
+ const status = this.send(message);
541
+ // Return the ping status.
542
+ return status;
543
+ }
544
+ /**
545
+ * Initiates the network connection negotiates a protocol version. Also emits the 'connect' signal if successful.
546
+ *
547
+ * @throws {Error} if the socket connection fails.
548
+ * @returns a promise resolving when the connection is established
549
+ */ async connect() {
550
+ // If we are already connected return true.
551
+ if (this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) return;
552
+ // Indicate that the connection is connecting
553
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTING;
554
+ // Define a function to wrap connection as a promise.
555
+ const connectionResolver = (resolve, reject)=>{
556
+ const rejector = (error)=>{
557
+ // Set the status back to disconnected
558
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED;
559
+ // Reject with the error as reason
560
+ reject(error);
561
+ };
562
+ // Replace previous error handlers to reject the promise on failure.
563
+ this.socket.removeAllListeners("error");
564
+ this.socket.once("error", rejector);
565
+ // Define a function to wrap version negotiation as a callback.
566
+ const versionNegotiator = ()=>{
567
+ // Write a log message to show that we have started version negotiation.
568
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Requesting protocol version ${this.version} with '${this.hostIdentifier}'.`);
569
+ // remove the one-time error handler since no error was detected.
570
+ this.socket.removeListener("error", rejector);
571
+ // Build a version negotiation message.
572
+ const versionMessage = (0, $c78f59d21170b7a6$export$2e2bcd8739ae039).buildRequestObject("server.version", [
573
+ this.application,
574
+ this.version
575
+ ], "versionNegotiation");
576
+ // Define a function to wrap version validation as a function.
577
+ const versionValidator = (version)=>{
578
+ // Check if version negotiation failed.
579
+ if ((0, $a192ea5a4eec42d4$export$e1f38ab2b4ebdde6)(version)) {
580
+ // Disconnect from the host.
581
+ this.disconnect(true);
582
+ // Declare an error message.
583
+ const errorMessage = "unsupported protocol version.";
584
+ // Log the error.
585
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);
586
+ // Reject the connection with false since version negotiation failed.
587
+ reject(errorMessage);
588
+ } else if (version.protocol !== this.version && `${version.protocol}.0` !== this.version && `${version.protocol}.0.0` !== this.version) {
589
+ // Disconnect from the host.
590
+ this.disconnect(true);
591
+ // Declare an error message.
592
+ const errorMessage = `incompatible protocol version negotiated (${version.protocol} !== ${this.version}).`;
593
+ // Log the error.
594
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);
595
+ // Reject the connection with false since version negotiation failed.
596
+ reject(errorMessage);
597
+ } else {
598
+ // Write a log message.
599
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Negotiated protocol version ${version.protocol} with '${this.hostIdentifier}', powered by ${version.software}.`);
600
+ // Set connection status to connected
601
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED;
602
+ // Emit a connect event now that the connection is usable.
603
+ this.emit("connect");
604
+ // Resolve the connection promise since we successfully connected and negotiated protocol version.
605
+ resolve();
606
+ }
607
+ };
608
+ // Listen for version negotiation once.
609
+ this.once("version", versionValidator);
610
+ // Send the version negotiation message.
611
+ this.send(versionMessage);
612
+ };
613
+ // Prepare the version negotiation.
614
+ this.socket.once("connect", versionNegotiator);
615
+ // Set up handler for network errors.
616
+ this.socket.on("error", this.onSocketError.bind(this));
617
+ // Connect to the server.
618
+ this.socket.connect(this.host, this.port, this.scheme, this.timeout);
619
+ };
620
+ // Wait until connection is established and version negotiation succeeds.
621
+ await new Promise(connectionResolver);
622
+ }
623
+ /**
624
+ * Restores the network connection.
625
+ */ async reconnect() {
626
+ // If a reconnect timer is set, remove it
627
+ await this.clearReconnectTimer();
628
+ // Write a log message.
629
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Trying to reconnect to '${this.hostIdentifier}'..`);
630
+ // Set the status to reconnecting for more accurate log messages.
631
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).RECONNECTING;
632
+ // Destroy and recreate the socket to get a clean slate.
633
+ this.destroySocket();
634
+ this.createSocket();
635
+ try {
636
+ // Try to connect again.
637
+ await this.connect();
638
+ } catch (error) {
639
+ // Do nothing as the error should be handled via the disconnect and error signals.
640
+ }
641
+ }
642
+ /**
643
+ * Removes the current reconnect timer.
644
+ */ clearReconnectTimer() {
645
+ // If a reconnect timer is set, remove it
646
+ if (this.timers.reconnect) clearTimeout(this.timers.reconnect);
647
+ // Reset the timer reference.
648
+ this.timers.reconnect = undefined;
649
+ }
650
+ /**
651
+ * Removes the current keep-alive timer.
652
+ */ clearKeepAliveTimer() {
653
+ // If a keep-alive timer is set, remove it
654
+ if (this.timers.keepAlive) clearTimeout(this.timers.keepAlive);
655
+ // Reset the timer reference.
656
+ this.timers.keepAlive = undefined;
657
+ }
658
+ /**
659
+ * Initializes the keep alive timer loop.
660
+ */ setupKeepAliveTimer() {
661
+ // If the keep-alive timer loop is not currently set up..
662
+ if (!this.timers.keepAlive) // Set a new keep-alive timer.
663
+ this.timers.keepAlive = setTimeout(this.ping.bind(this), this.pingInterval);
664
+ }
665
+ /**
666
+ * Tears down the current connection and removes all event listeners on disconnect.
667
+ *
668
+ * @param {boolean} force disconnect even if the connection has not been fully established yet.
669
+ * @param {boolean} intentional update connection state if disconnect is intentional.
670
+ *
671
+ * @returns true if successfully disconnected, or false if there was no connection.
672
+ */ async disconnect(force = false, intentional = true) {
673
+ // Return early when there is nothing to disconnect from
674
+ if (this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED && !force) // Return false to indicate that there was nothing to disconnect from.
675
+ return false;
676
+ // Update connection state if the disconnection is intentional.
677
+ // NOTE: The state is meant to represent what the client is requesting, but
678
+ // is used internally to handle visibility changes in browsers to ensure functional reconnection.
679
+ if (intentional) // Set connection status to null to indicate tear-down is currently happening.
680
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTING;
681
+ // If a keep-alive timer is set, remove it.
682
+ await this.clearKeepAliveTimer();
683
+ // If a reconnect timer is set, remove it
684
+ await this.clearReconnectTimer();
685
+ const disconnectResolver = (resolve)=>{
686
+ // Resolve to true after the connection emits a disconnect
687
+ this.once("disconnect", ()=>resolve(true));
688
+ // Close the connection and destroy the socket.
689
+ this.destroySocket();
690
+ };
691
+ // Return true to indicate that we disconnected.
692
+ return new Promise(disconnectResolver);
693
+ }
694
+ /**
695
+ * Updates connection state based on application visibility.
696
+ *
697
+ * Some browsers will disconnect network connections when the browser is out of focus,
698
+ * which would normally cause our reconnect-on-timeout routines to trigger, but that
699
+ * results in a poor user experience since the events are not handled consistently
700
+ * and sometimes it can take some time after restoring focus to the browser.
701
+ *
702
+ * By manually disconnecting when this happens we prevent the default reconnection routines
703
+ * and make the behavior consistent across browsers.
704
+ */ async handleVisibilityChange() {
705
+ // Disconnect when application is removed from focus.
706
+ if (document.visibilityState === "hidden") {
707
+ const forceDisconnect = true;
708
+ const isIntended = false;
709
+ this.disconnect(forceDisconnect, isIntended);
710
+ }
711
+ // Reconnect when application is returned to focus.
712
+ if (document.visibilityState === "visible") this.reconnect();
713
+ }
714
+ /**
715
+ * Sends an arbitrary message to the server.
716
+ *
717
+ * @param {string} message json encoded request object to send to the server, as a string.
718
+ *
719
+ * @returns true if the message was fully flushed to the socket, false if part of the message
720
+ * is queued in the user memory
721
+ */ send(message) {
722
+ // Remove the current keep-alive timer if it exists.
723
+ this.clearKeepAliveTimer();
724
+ // Get the current timestamp in milliseconds.
725
+ const currentTime = Date.now();
726
+ // Follow up and verify that the message got sent..
727
+ const verificationTimer = setTimeout(this.verifySend.bind(this, currentTime), this.timeout);
728
+ // Store the verification timer locally so that it can be cleared when data has been received.
729
+ this.verifications.push(verificationTimer);
730
+ // Set a new keep-alive timer.
731
+ this.setupKeepAliveTimer();
732
+ // Write the message to the network socket.
733
+ return this.socket.write(message + (0, $c78f59d21170b7a6$export$2e2bcd8739ae039).statementDelimiter);
734
+ }
735
+ // --- Event managers. --- //
736
+ /**
737
+ * Marks the connection as timed out and schedules reconnection if we have not
738
+ * received data within the expected time frame.
739
+ */ verifySend(sentTimestamp) {
740
+ // If we haven't received any data since we last sent data out..
741
+ if (Number(this.lastReceivedTimestamp) < sentTimestamp) {
742
+ // If this connection is already disconnected, we do not change anything
743
+ if (this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED || this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTING) {
744
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Tried to verify already disconnected connection to '${this.hostIdentifier}'`);
745
+ return;
746
+ }
747
+ // Remove the current keep-alive timer if it exists.
748
+ this.clearKeepAliveTimer();
749
+ // Write a notification to the logs.
750
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Connection to '${this.hostIdentifier}' timed out.`);
751
+ // Close the connection to avoid re-use.
752
+ // NOTE: This initiates reconnection routines if the connection has not
753
+ // been marked as intentionally disconnected.
754
+ this.socket.disconnect();
755
+ }
756
+ }
757
+ /**
758
+ * Updates the connection status when a connection is confirmed.
759
+ */ onSocketConnect() {
760
+ // If a reconnect timer is set, remove it.
761
+ this.clearReconnectTimer();
762
+ // Set up the initial timestamp for when we last received data from the server.
763
+ this.lastReceivedTimestamp = Date.now();
764
+ // Set up the initial keep-alive timer.
765
+ this.setupKeepAliveTimer();
766
+ // Clear all temporary error listeners.
767
+ this.socket.removeAllListeners("error");
768
+ // Set up handler for network errors.
769
+ this.socket.on("error", this.onSocketError.bind(this));
770
+ }
771
+ /**
772
+ * Updates the connection status when a connection is ended.
773
+ */ onSocketDisconnect() {
774
+ // Send a disconnect signal higher up the stack.
775
+ this.emit("disconnect");
776
+ // Remove the current keep-alive timer if it exists.
777
+ this.clearKeepAliveTimer();
778
+ // If this is a connection we're trying to tear down..
779
+ if (this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTING) {
780
+ // If a reconnect timer is set, remove it.
781
+ this.clearReconnectTimer();
782
+ // Remove all event listeners
783
+ this.removeAllListeners();
784
+ // Mark the connection as disconnected.
785
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED;
786
+ // Write a log message.
787
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Disconnected from '${this.hostIdentifier}'.`);
788
+ } else {
789
+ // If this is for an established connection..
790
+ if (this.status === (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) // Write a notification to the logs.
791
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Connection with '${this.hostIdentifier}' was closed, trying to reconnect in ${this.reconnectInterval / 1000} seconds.`);
792
+ // Mark the connection as disconnected for now..
793
+ this.status = (0, $a58372b18a18806e$export$7516420eb880ab68).DISCONNECTED;
794
+ // If we don't have a pending reconnection timer..
795
+ if (!this.timers.reconnect) // Attempt to reconnect after one keep-alive duration.
796
+ this.timers.reconnect = setTimeout(this.reconnect.bind(this), this.reconnectInterval);
797
+ }
798
+ }
799
+ /**
800
+ * Notify administrator of any unexpected errors.
801
+ */ onSocketError(error) {
802
+ // Report a generic error if no error information is present.
803
+ // NOTE: When using WSS, the error event explicitly
804
+ // only allows to send a "simple" event without data.
805
+ // https://stackoverflow.com/a/18804298
806
+ if (typeof error === "undefined") // Do nothing, and instead rely on the socket disconnect event for further information.
807
+ return;
808
+ // If the DNS lookup failed.
809
+ if (error.code === "EAI_AGAIN") {
810
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Failed to look up DNS records for '${this.host}'.`);
811
+ return;
812
+ }
813
+ // If the connection timed out..
814
+ if (error.code === "ETIMEDOUT") {
815
+ // Log the provided timeout message.
816
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(error.message);
817
+ return;
818
+ }
819
+ // Log unknown error
820
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).errors(`Unknown network error ('${this.hostIdentifier}'): `, error);
821
+ }
822
+ }
823
+ var // Export the connection.
824
+ $1326c18f93f95fee$export$2e2bcd8739ae039 = $1326c18f93f95fee$var$ElectrumConnection;
825
+
826
+
827
+
828
+
829
+
830
+
831
+ // Acceptable parameter types for RPC messages
832
+ const $7c0fb93e8eea922a$export$d73a2e87a509880 = function(message) {
833
+ return "id" in message && "error" in message;
834
+ };
835
+ const $7c0fb93e8eea922a$export$81276773828ff315 = function(message) {
836
+ return "id" in message && "result" in message;
837
+ };
838
+ const $7c0fb93e8eea922a$export$280de919a0cf6928 = function(message) {
839
+ return !("id" in message) && "method" in message;
840
+ };
841
+ const $7c0fb93e8eea922a$export$94e3360fcddccc76 = function(message) {
842
+ return "id" in message && "method" in message;
843
+ };
844
+
845
+
846
+
847
+ /**
848
+ * Triggers when the underlying connection is established.
849
+ *
850
+ * @event ElectrumClient#connected
851
+ */ /**
852
+ * Triggers when the underlying connection is lost.
853
+ *
854
+ * @event ElectrumClient#disconnected
855
+ */ /**
856
+ * Triggers when the remote server sends data that is not a request response.
857
+ *
858
+ * @event ElectrumClient#notification
859
+ */ /**
860
+ * High-level Electrum client that lets applications send requests and subscribe to notification events from a server.
861
+ */ class $620a18299ef8d6fd$var$ElectrumClient extends (0, $4QiMX$EventEmitter) {
862
+ /**
863
+ * Initializes an Electrum client.
864
+ *
865
+ * @param {string} application your application name, used to identify to the electrum host.
866
+ * @param {string} version protocol version to use with the host.
867
+ * @param {string} host fully qualified domain name or IP number of the host.
868
+ * @param {number} port the TCP network port of the host.
869
+ * @param {TransportScheme} scheme the transport scheme to use for connection
870
+ * @param {number} timeout how long network delays we will wait for before taking action, in milliseconds.
871
+ * @param {number} pingInterval the time between sending pings to the electrum host, in milliseconds.
872
+ * @param {number} reconnectInterval the time between reconnection attempts to the electrum host, in milliseconds.
873
+ * @param {boolean} useBigInt whether to use bigint for numbers in json response.
874
+ *
875
+ * @throws {Error} if `version` is not a valid version string.
876
+ */ constructor(application, version, host, port = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PORT, scheme = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TRANSPORT_SCHEME, timeout = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TIMEOUT, pingInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PING_INTERVAL, reconnectInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).RECONNECT, useBigInt = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).USE_BIG_INT){
877
+ // Initialize the event emitter.
878
+ super();
879
+ // Initialize an empty list of subscription metadata.
880
+ this.subscriptionMethods = {};
881
+ // Start counting the request IDs from 0
882
+ this.requestId = 0;
883
+ // Initialize an empty dictionary for keeping track of request resolvers
884
+ this.requestResolvers = {};
885
+ // Mutex lock used to prevent simultaneous connect() and disconnect() calls.
886
+ this.connectionLock = new (0, $4QiMX$Mutex)();
887
+ // Set up a connection to an electrum server.
888
+ this.connection = new (0, $1326c18f93f95fee$export$2e2bcd8739ae039)(application, version, host, port, scheme, timeout, pingInterval, reconnectInterval, useBigInt);
889
+ }
890
+ /**
891
+ * Connects to the remote server.
892
+ *
893
+ * @throws {Error} if the socket connection fails.
894
+ * @returns a promise resolving when the connection is established.
895
+ */ async connect() {
896
+ // Create a lock so that multiple connects/disconnects cannot race each other.
897
+ const unlock = await this.connectionLock.acquire();
898
+ try {
899
+ // If we are already connected, do not attempt to connect again.
900
+ if (this.connection.status === (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) return;
901
+ // Listen for parsed statements.
902
+ this.connection.on("statement", this.response.bind(this));
903
+ // Hook up resubscription on connection.
904
+ this.connection.on("connect", this.resubscribeOnConnect.bind(this));
905
+ // Relay connect and disconnect events.
906
+ this.connection.on("connect", this.emit.bind(this, "connected"));
907
+ this.connection.on("disconnect", this.onConnectionDisconnect.bind(this));
908
+ // Relay error events.
909
+ this.connection.on("error", this.emit.bind(this, "error"));
910
+ // Connect with the server.
911
+ await this.connection.connect();
912
+ } finally{
913
+ unlock();
914
+ }
915
+ }
916
+ /**
917
+ * Disconnects from the remote server and removes all event listeners/subscriptions and open requests.
918
+ *
919
+ * @param {boolean} force disconnect even if the connection has not been fully established yet.
920
+ * @param {boolean} retainSubscriptions retain subscription data so they will be restored on reconnection.
921
+ *
922
+ * @returns true if successfully disconnected, or false if there was no connection.
923
+ */ async disconnect(force = false, retainSubscriptions = false) {
924
+ // Create a lock so that multiple connects/disconnects cannot race each other.
925
+ const unlock = await this.connectionLock.acquire();
926
+ try {
927
+ if (!retainSubscriptions) {
928
+ // Cancel all event listeners.
929
+ this.removeAllListeners();
930
+ // Remove all subscription data
931
+ this.subscriptionMethods = {};
932
+ }
933
+ // For each pending request..
934
+ for(const index in this.requestResolvers){
935
+ // Reject the request.
936
+ const requestResolver = this.requestResolvers[index];
937
+ requestResolver(new Error("Manual disconnection"));
938
+ // Remove the request.
939
+ delete this.requestResolvers[index];
940
+ }
941
+ // Disconnect from the remove server.
942
+ return await this.connection.disconnect(force);
943
+ } finally{
944
+ unlock();
945
+ }
946
+ }
947
+ /**
948
+ * Calls a method on the remote server with the supplied parameters.
949
+ *
950
+ * @param {string} method name of the method to call.
951
+ * @param {...string} parameters one or more parameters for the method.
952
+ *
953
+ * @throws {Error} if the client is disconnected.
954
+ * @returns a promise that resolves with the result of the method or an Error.
955
+ */ async request(method, ...parameters) {
956
+ // If we are not connected to a server..
957
+ if (this.connection.status !== (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) // Reject the request with a disconnected error message.
958
+ throw new Error(`Unable to send request to a disconnected server '${this.connection.host}'.`);
959
+ // Increase the request ID by one.
960
+ this.requestId += 1;
961
+ // Store a copy of the request id.
962
+ const id = this.requestId;
963
+ // Format the arguments as an electrum request object.
964
+ const message = (0, $c78f59d21170b7a6$export$2e2bcd8739ae039).buildRequestObject(method, parameters, id);
965
+ // Define a function to wrap the request in a promise.
966
+ const requestResolver = (resolve)=>{
967
+ // Add a request resolver for this promise to the list of requests.
968
+ this.requestResolvers[id] = (error, data)=>{
969
+ // If the resolution failed..
970
+ if (error) // Resolve the promise with the error for the application to handle.
971
+ resolve(error);
972
+ else // Resolve the promise with the request results.
973
+ resolve(data);
974
+ };
975
+ // Send the request message to the remote server.
976
+ this.connection.send(message);
977
+ };
978
+ // Write a log message.
979
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).network(`Sending request '${method}' to '${this.connection.host}'`);
980
+ // return a promise to deliver results later.
981
+ return new Promise(requestResolver);
982
+ }
983
+ /**
984
+ * Subscribes to the method and payload at the server.
985
+ *
986
+ * @note the response for the subscription request is issued as a notification event.
987
+ *
988
+ * @param {string} method one of the subscribable methods the server supports.
989
+ * @param {...string} parameters one or more parameters for the method.
990
+ *
991
+ * @throws {Error} if the client is disconnected.
992
+ * @returns a promise resolving when the subscription is established.
993
+ */ async subscribe(method, ...parameters) {
994
+ // Initialize an empty list of subscription payloads, if needed.
995
+ if (!this.subscriptionMethods[method]) this.subscriptionMethods[method] = new Set();
996
+ // Store the subscription parameters to track what data we have subscribed to.
997
+ this.subscriptionMethods[method].add(JSON.stringify(parameters));
998
+ // Send initial subscription request.
999
+ const requestData = await this.request(method, ...parameters);
1000
+ // Construct a notification structure to package the initial result as a notification.
1001
+ const notification = {
1002
+ jsonrpc: "2.0",
1003
+ method: method,
1004
+ params: [
1005
+ ...parameters,
1006
+ requestData
1007
+ ]
1008
+ };
1009
+ // Manually emit an event for the initial response.
1010
+ this.emit("notification", notification);
1011
+ }
1012
+ /**
1013
+ * Unsubscribes to the method at the server and removes any callback functions
1014
+ * when there are no more subscriptions for the method.
1015
+ *
1016
+ * @param {string} method a previously subscribed to method.
1017
+ * @param {...string} parameters one or more parameters for the method.
1018
+ *
1019
+ * @throws {Error} if no subscriptions exist for the combination of the provided `method` and `parameters.
1020
+ * @throws {Error} if the client is disconnected.
1021
+ * @returns a promise resolving when the subscription is removed.
1022
+ */ async unsubscribe(method, ...parameters) {
1023
+ // Throw an error if the client is disconnected.
1024
+ if (this.connection.status !== (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) throw new Error(`Unable to send unsubscribe request to a disconnected server '${this.connection.host}'.`);
1025
+ // If this method has no subscriptions..
1026
+ if (!this.subscriptionMethods[method]) // Reject this promise with an explanation.
1027
+ throw new Error(`Cannot unsubscribe from '${method}' since the method has no subscriptions.`);
1028
+ // Pack up the parameters as a long string.
1029
+ const subscriptionParameters = JSON.stringify(parameters);
1030
+ // If the method payload could not be located..
1031
+ if (!this.subscriptionMethods[method].has(subscriptionParameters)) // Reject this promise with an explanation.
1032
+ throw new Error(`Cannot unsubscribe from '${method}' since it has no subscription with the given parameters.`);
1033
+ // Remove this specific subscription payload from internal tracking.
1034
+ this.subscriptionMethods[method].delete(subscriptionParameters);
1035
+ // Send unsubscription request to the server
1036
+ // NOTE: As a convenience we allow users to define the method as the subscribe or unsubscribe version.
1037
+ await this.request(method.replace(".subscribe", ".unsubscribe"), ...parameters);
1038
+ // Write a log message.
1039
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).client(`Unsubscribed from '${String(method)}' for the '${subscriptionParameters}' parameters.`);
1040
+ }
1041
+ /**
1042
+ * Restores existing subscriptions without updating status or triggering manual callbacks.
1043
+ *
1044
+ * @throws {Error} if subscription data cannot be found for all stored event names.
1045
+ * @throws {Error} if the client is disconnected.
1046
+ * @returns a promise resolving to true when the subscriptions are restored.
1047
+ *
1048
+ * @ignore
1049
+ */ async resubscribeOnConnect() {
1050
+ // Write a log message.
1051
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).client(`Connected to '${this.connection.hostIdentifier}'.`);
1052
+ // Initialize an empty list of resubscription promises.
1053
+ const resubscriptionPromises = [];
1054
+ // For each method we have a subscription for..
1055
+ for(const method in this.subscriptionMethods){
1056
+ // .. and for each parameter we have previously been subscribed to..
1057
+ for (const parameterJSON of this.subscriptionMethods[method].values()){
1058
+ // restore the parameters from JSON.
1059
+ const parameters = JSON.parse(parameterJSON);
1060
+ // Send a subscription request.
1061
+ resubscriptionPromises.push(this.subscribe(method, ...parameters));
1062
+ }
1063
+ // Wait for all re-subscriptions to complete.
1064
+ await Promise.all(resubscriptionPromises);
1065
+ }
1066
+ // Write a log message if there was any subscriptions to restore.
1067
+ if (resubscriptionPromises.length > 0) (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).client(`Restored ${resubscriptionPromises.length} previous subscriptions for '${this.connection.hostIdentifier}'`);
1068
+ }
1069
+ /**
1070
+ * Parser messages from the remote server to resolve request promises and emit subscription events.
1071
+ *
1072
+ * @param {RPCNotification | RPCResponse} message the response message
1073
+ *
1074
+ * @throws {Error} if the message ID does not match an existing request.
1075
+ * @ignore
1076
+ */ response(message) {
1077
+ // If the received message is a notification, we forward it to all event listeners
1078
+ if ((0, $7c0fb93e8eea922a$export$280de919a0cf6928)(message)) {
1079
+ // Write a log message.
1080
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).client(`Received notification for '${message.method}' from '${this.connection.host}'`);
1081
+ // Forward the message content to all event listeners.
1082
+ this.emit("notification", message);
1083
+ // Return since it does not have an associated request resolver
1084
+ return;
1085
+ }
1086
+ // If the response ID is null we cannot use it to index our request resolvers
1087
+ if (message.id === null) // Throw an internal error, this should not happen.
1088
+ throw new Error("Internal error: Received an RPC response with ID null.");
1089
+ // Look up which request promise we should resolve this.
1090
+ const requestResolver = this.requestResolvers[message.id];
1091
+ // If we do not have a request resolver for this response message..
1092
+ if (!requestResolver) // Throw an internal error, this should not happen.
1093
+ throw new Error("Internal error: Callback for response not available.");
1094
+ // Remove the promise from the request list.
1095
+ delete this.requestResolvers[message.id];
1096
+ // If the message contains an error..
1097
+ if ((0, $7c0fb93e8eea922a$export$d73a2e87a509880)(message)) // Forward the message error to the request resolver and omit the `result` parameter.
1098
+ requestResolver(new Error(message.error.message));
1099
+ else // Forward the message content to the request resolver and omit the `error` parameter
1100
+ // (by setting it to undefined).
1101
+ requestResolver(undefined, message.result);
1102
+ }
1103
+ /**
1104
+ * Callback function that is called when connection to the Electrum server is lost.
1105
+ * Aborts all active requests with an error message indicating that connection was lost.
1106
+ *
1107
+ * @ignore
1108
+ */ onConnectionDisconnect() {
1109
+ // Emit a disconnection signal to any listeners.
1110
+ this.emit("disconnected");
1111
+ // Loop over active requests
1112
+ for(const resolverId in this.requestResolvers){
1113
+ // Extract request resolver for readability
1114
+ const requestResolver = this.requestResolvers[resolverId];
1115
+ // Resolve the active request with an error indicating that the connection was lost.
1116
+ requestResolver(new Error("Connection lost"));
1117
+ // Remove the promise from the request list.
1118
+ delete this.requestResolvers[resolverId];
1119
+ }
1120
+ }
1121
+ }
1122
+ var // Export the client.
1123
+ $620a18299ef8d6fd$export$2e2bcd8739ae039 = $620a18299ef8d6fd$var$ElectrumClient;
1124
+
1125
+
1126
+
1127
+
1128
+
1129
+
1130
+
1131
+
1132
+
1133
+ /**
1134
+ * Triggers when the cluster connects to enough servers to satisfy both the cluster confidence and distribution policies.
1135
+ *
1136
+ * @event ElectrumCluster#ready
1137
+ * @deprecated
1138
+ */ /**
1139
+ * Triggers when the cluster loses a connection and can no longer satisfy the cluster distribution policy.
1140
+ *
1141
+ * @event ElectrumCluster#degraded
1142
+ * @deprecated
1143
+ */ /**
1144
+ * Triggers when the cluster loses a connection and can no longer satisfy the cluster confidence policy.
1145
+ *
1146
+ * @event ElectrumCluster#disabled
1147
+ * @deprecated
1148
+ */ /**
1149
+ * Triggers when the cluster verifies the integrity of remote server sent data that is not a request responses.
1150
+ *
1151
+ * @event ElectrumCluster#notification
1152
+ * @deprecated
1153
+ */ /**
1154
+ * High-level electrum client that provides transparent load balancing, confidence checking and/or low-latency polling.
1155
+ * @deprecated
1156
+ */ class $9b2ed2eb52532075$var$ElectrumCluster extends (0, $4QiMX$EventEmitter) {
1157
+ /**
1158
+ * @param {string} application your application name, used to identify to the electrum hosts.
1159
+ * @param {string} version protocol version to use with the hosts.
1160
+ * @param {number} confidence wait for this number of hosts to provide identical results.
1161
+ * @param {number} distribution request information from this number of hosts.
1162
+ * @param {ClusterOrder} order select hosts to communicate with in this order.
1163
+ * @param {number} timeout how long network delays we will wait for before taking action, in milliseconds.
1164
+ * @param {number} pingInterval the time between sending pings to the electrum host, in milliseconds.
1165
+ * @param {number} reconnectInterval the time between reconnection attempts to the electrum host, in milliseconds.
1166
+ * @param {boolean} useBigInt whether to use bigint for numbers in json response.
1167
+ */ constructor(application, version, confidence = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).CLUSTER_CONFIDENCE, distribution = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).CLUSTER_DISTRIBUTION, order = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).CLUSTER_ORDER, timeout = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TIMEOUT, pingInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PING_INTERVAL, reconnectInterval = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).RECONNECT, useBigInt = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).USE_BIG_INT){
1168
+ // Initialize the event emitter.
1169
+ super();
1170
+ this.application = application;
1171
+ this.version = version;
1172
+ this.confidence = confidence;
1173
+ this.distribution = distribution;
1174
+ this.order = order;
1175
+ this.timeout = timeout;
1176
+ this.pingInterval = pingInterval;
1177
+ this.reconnectInterval = reconnectInterval;
1178
+ this.useBigInt = useBigInt;
1179
+ this.// Initialize an empty dictionary of clients in the cluster
1180
+ clients = {};
1181
+ this.// Start at 0 connected clients
1182
+ connections = 0;
1183
+ this.// Set up an empty set of notification data.
1184
+ notifications = {};
1185
+ this.// Start the cluster in DISABLED state
1186
+ status = (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DISABLED;
1187
+ this.// Start counting request IDs at 0
1188
+ requestCounter = 0;
1189
+ this.// Initialize an empty dictionary for keeping track of request resolvers
1190
+ requestPromises = {};
1191
+ this.// Lock to prevent concurrency race conditions when sending requests.
1192
+ requestLock = new (0, $4QiMX$Mutex)();
1193
+ this.// Lock to prevent concurrency race conditions when receiving responses.
1194
+ responseLock = new (0, $4QiMX$Mutex)();
1195
+ // Write a log message.
1196
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Initialized empty cluster (${confidence} of ${distribution || "ALL"})`);
1197
+ // Print out a warning if we cannot guarantee consensus for subscription notifications.
1198
+ // Case 1: we don't know how many servers will be used, so warning just to be safe
1199
+ // Case 2: we know the number of servers needed to trust a response is less than 50%.
1200
+ if (distribution === (0, $a58372b18a18806e$export$436a960acc41e848).ALL || confidence / distribution <= 0.50) (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).warning(`Subscriptions might return multiple valid responses when confidence (${confidence}) is less than 51% of distribution.`);
1201
+ }
1202
+ /**
1203
+ * Adds a server to the cluster.
1204
+ * @deprecated
1205
+ *
1206
+ * @param {string} host fully qualified domain name or IP number of the host.
1207
+ * @param {number} port the TCP network port of the host.
1208
+ * @param {TransportScheme} scheme the transport scheme to use for connection
1209
+ * @param {boolean} autoConnect flag indicating whether the server should automatically connect (default true)
1210
+ *
1211
+ * @throws {Error} if the cluster's version is not a valid version string.
1212
+ * @returns a promise that resolves when the connection has been initiated.
1213
+ */ async addServer(host, port = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).PORT, scheme = (0, $5abc8fb342687c03$export$f019be48b3aacb1a).TRANSPORT_SCHEME, autoConnect = true) {
1214
+ // Set up a new electrum client.
1215
+ const client = new (0, $620a18299ef8d6fd$export$2e2bcd8739ae039)(this.application, this.version, host, port, scheme, this.timeout, this.pingInterval, this.reconnectInterval, this.useBigInt);
1216
+ // Define the client identity to avoid repetition.
1217
+ const clientIdentity = `${host}:${port}`;
1218
+ // Store this client.
1219
+ this.clients[clientIdentity] = {
1220
+ state: (0, $a58372b18a18806e$export$c4f81c6d30ca200f).UNAVAILABLE,
1221
+ connection: client
1222
+ };
1223
+ /**
1224
+ * Define a helper function to evaluate and log cluster status.
1225
+ *
1226
+ * @fires ElectrumCluster#ready
1227
+ * @fires ElectrumCluster#degraded
1228
+ * @fires ElectrumCluster#disabled
1229
+ */ const updateClusterStatus = ()=>{
1230
+ // Calculate the required distribution, taking into account that distribution to all is represented with 0.
1231
+ const distribution = Math.max(this.confidence, this.distribution);
1232
+ // Check if we have enough connections to saturate distribution.
1233
+ if (this.connections >= distribution) // If the cluster is not currently considered ready..
1234
+ {
1235
+ if (this.status !== (0, $a58372b18a18806e$export$c66b56bc0ff967ca).READY) {
1236
+ // Mark the cluster as ready.
1237
+ this.status = (0, $a58372b18a18806e$export$c66b56bc0ff967ca).READY;
1238
+ // Emit the ready signal to indicate the cluster is running in a ready mode.
1239
+ this.emit("ready");
1240
+ // Write a log message with an update on the current cluster status.
1241
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Cluster status is ready (currently ${this.connections} of ${distribution} connections available.)`);
1242
+ }
1243
+ } else if (this.connections >= this.confidence) // If the cluster is not currently considered degraded..
1244
+ {
1245
+ if (this.status !== (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DEGRADED) {
1246
+ // Mark the cluster as degraded.
1247
+ this.status = (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DEGRADED;
1248
+ // Emit the degraded signal to indicate the cluster is running in a degraded mode.
1249
+ this.emit("degraded");
1250
+ // Write a log message with an update on the current cluster status.
1251
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Cluster status is degraded (only ${this.connections} of ${distribution} connections available.)`);
1252
+ }
1253
+ } else if (this.status !== (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DISABLED) {
1254
+ // Mark the cluster as disabled.
1255
+ this.status = (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DISABLED;
1256
+ // Emit the degraded signal to indicate the cluster is disabled.
1257
+ this.emit("disabled");
1258
+ // Write a log message with an update on the current cluster status.
1259
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Cluster status is disabled (only ${this.connections} of the ${distribution} connections are available.)`);
1260
+ }
1261
+ };
1262
+ // Define a function to run when client has connected.
1263
+ const onConnect = async ()=>{
1264
+ // Wrap in a try-catch so we can ignore errors.
1265
+ try {
1266
+ // Check connection status
1267
+ const connectionStatus = client.connection.status;
1268
+ // If the connection is fine..
1269
+ if (connectionStatus === (0, $a58372b18a18806e$export$7516420eb880ab68).CONNECTED) {
1270
+ // If this was from an unavailable connection..
1271
+ if (this.clients[clientIdentity].state === (0, $a58372b18a18806e$export$c4f81c6d30ca200f).UNAVAILABLE) // Update connection counter.
1272
+ this.connections += 1;
1273
+ // Set client state to available.
1274
+ this.clients[clientIdentity].state = (0, $a58372b18a18806e$export$c4f81c6d30ca200f).AVAILABLE;
1275
+ // update the cluster status.
1276
+ updateClusterStatus();
1277
+ }
1278
+ } catch (error) {
1279
+ // Do nothing.
1280
+ }
1281
+ };
1282
+ // Define a function to run when client disconnects.
1283
+ const onDisconnect = ()=>{
1284
+ // If this was from an established connection..
1285
+ if (this.clients[clientIdentity].state === (0, $a58372b18a18806e$export$c4f81c6d30ca200f).AVAILABLE) // Update connection counter.
1286
+ this.connections -= 1;
1287
+ // Set client state to unavailable.
1288
+ this.clients[clientIdentity].state = (0, $a58372b18a18806e$export$c4f81c6d30ca200f).UNAVAILABLE;
1289
+ // update the cluster status.
1290
+ updateClusterStatus();
1291
+ };
1292
+ // Set up handlers for connection and disconnection.
1293
+ client.connection.on("connect", onConnect.bind(this));
1294
+ client.connection.on("disconnect", onDisconnect.bind(this));
1295
+ // Set up handler for notification events, that includes the identity of this client so it can be tracked.
1296
+ client.on("notification", this.handleSubscriptionNotifications.bind(this, clientIdentity));
1297
+ // Connect if auto-connect is set to true, returning the connection result.
1298
+ if (autoConnect) try {
1299
+ // Set up the connection.
1300
+ await client.connect();
1301
+ } catch (error) {
1302
+ // Log a message why the connection failed and move on.
1303
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Failed to connect with ${host}: ${error}`);
1304
+ }
1305
+ }
1306
+ /**
1307
+ * Calls a method on the remote server with the supplied parameters.
1308
+ * @deprecated
1309
+ *
1310
+ * @param {string} method name of the method to call.
1311
+ * @param {...string} parameters one or more parameters for the method.
1312
+ *
1313
+ * @throws {Error} if not enough clients are connected
1314
+ * @throws {Error} if no response is received with sufficient integrity
1315
+ * @returns a promise that resolves with the result of the method.
1316
+ */ async request(method, ...parameters) {
1317
+ // Check if the cluster is unable to serve requests.
1318
+ if (this.status === (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DISABLED) throw new Error(`Cannot request '${method}' when available clients (${this.connections}) is less than required confidence (${this.confidence}).`);
1319
+ // Lock this request method temporarily.
1320
+ const unlock = await this.requestLock.acquire();
1321
+ // Declare requestId outside of try-catch scope.
1322
+ let requestId = 0;
1323
+ // NOTE: If this async method is called very rapidly, it's theoretically possible that the parts below could interfere.
1324
+ try {
1325
+ // Increase the current request counter.
1326
+ this.requestCounter += 1;
1327
+ // Copy the request counter so we can work with the copy and know it won't change
1328
+ // even if the request counter is raised from concurrent requests.
1329
+ requestId = this.requestCounter;
1330
+ } finally{
1331
+ // Unlock this request method now that the concurrency sensitive condition is completed.
1332
+ unlock();
1333
+ }
1334
+ // Initialize an empty list of request promises.
1335
+ this.requestPromises[requestId] = [];
1336
+ // Extract all available client IDs
1337
+ const availableClientIDs = Object.keys(this.clients).filter((clientID)=>this.clients[clientID].state === (0, $a58372b18a18806e$export$c4f81c6d30ca200f).AVAILABLE);
1338
+ // Initialize a sent counter.
1339
+ let sentCounter = 0;
1340
+ // Determine the number of clients we need to send to, taking ClusterDistribution.ALL (=0) into account.
1341
+ let requiredDistribution = this.distribution || availableClientIDs.length;
1342
+ // If the cluster is in degraded status, we do not have enough available clients to
1343
+ // match distribution, but still enough to reach consensus, so we use the clients we have.
1344
+ if (this.status === (0, $a58372b18a18806e$export$c66b56bc0ff967ca).DEGRADED) requiredDistribution = availableClientIDs.length;
1345
+ // Repeat until we have sent the request to the desired number of clients.
1346
+ while(sentCounter < requiredDistribution){
1347
+ // Pick an array index according to our ordering strategy.
1348
+ let currentIndex = 0;
1349
+ // Use a random array index when cluster order is set to RANDOM
1350
+ if (this.order === (0, $a58372b18a18806e$export$161fe3707f756bf9).RANDOM) currentIndex = Math.floor(Math.random() * availableClientIDs.length);
1351
+ // Move a client identity from the client list to its own variable.
1352
+ const [currentClient] = availableClientIDs.splice(currentIndex, 1);
1353
+ // Send the request to the client and store the request promise.
1354
+ const requestPromise = this.clients[currentClient].connection.request(method, ...parameters);
1355
+ this.requestPromises[requestId].push(requestPromise);
1356
+ // Increase the sent counter.
1357
+ sentCounter += 1;
1358
+ }
1359
+ // Define a function to poll for request responses.
1360
+ const pollResponse = (resolve, reject)=>{
1361
+ // Define a function to resolve request responses based on integrity.
1362
+ const resolveRequest = async ()=>{
1363
+ // Set up an empty set of response data.
1364
+ const responseData = {};
1365
+ // Set up a counter to keep track of how many responses we have checked.
1366
+ let checkedResponses = 0;
1367
+ // For each server we issued a request to..
1368
+ for(const currentPromise in this.requestPromises[requestId]){
1369
+ // Initialize a holder for the response in the required scope to use it.
1370
+ let response;
1371
+ // Race the request promise against a pre-resolved request to determine request status.
1372
+ try {
1373
+ // Arrange an array of the current promise and an empty promise such that..
1374
+ const promises = [
1375
+ this.requestPromises[requestId][currentPromise],
1376
+ Promise.resolve(undefined)
1377
+ ];
1378
+ // .. we can get the result of the current promise if it is currently resolved, but don't need to wait for it otherwise.
1379
+ response = await Promise.race(promises);
1380
+ } // Handle case where the request sent resulted in a thrown error / promise rejection, rather then resolving to a response.
1381
+ // Note that in the worst time case, each request can be expected to eventually throw an error on timeout.
1382
+ catch (error) {
1383
+ // Increase the counter for checked responses.
1384
+ checkedResponses += 1;
1385
+ continue;
1386
+ }
1387
+ // If the promise is settled..
1388
+ if (response !== undefined) {
1389
+ // Calculate a unique identifier for this notification data.
1390
+ const responseDataIdentifier = (0, $4QiMX$stringify)(response);
1391
+ // Increase the counter for checked responses.
1392
+ checkedResponses += 1;
1393
+ // Either set the response data counter or increase it.
1394
+ if (responseData[responseDataIdentifier] === undefined) responseData[responseDataIdentifier] = 1;
1395
+ else responseData[responseDataIdentifier] += 1;
1396
+ // Check if this response has enough integrity according to our confidence strategy.
1397
+ if (responseData[responseDataIdentifier] === this.confidence) {
1398
+ // Write log entry.
1399
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Validated response for '${method}' with sufficient integrity (${this.confidence}).`);
1400
+ // Resolve the request with this response.
1401
+ resolve(response);
1402
+ // Return after resolving since we do not want to continue the execution.
1403
+ return;
1404
+ }
1405
+ }
1406
+ }
1407
+ // If all clients have responded but we failed to reach desired integrity..
1408
+ if (checkedResponses === this.requestPromises[requestId].length) {
1409
+ // Reject this request with an error message.
1410
+ reject(new Error(`Unable to complete request for '${method}', response failed to reach sufficient integrity (${this.confidence}).`));
1411
+ // Return after rejecting since we do not want to continue the execution.
1412
+ return;
1413
+ }
1414
+ // If we are not ready, but have not timed out and should wait more..
1415
+ setTimeout(resolveRequest, 1000);
1416
+ };
1417
+ // Attempt the initial resolution of the request.
1418
+ resolveRequest();
1419
+ };
1420
+ // return some kind of promise that resolves when integrity number of clients results match.
1421
+ return new Promise(pollResponse);
1422
+ }
1423
+ /**
1424
+ * Subscribes to the method at the cluster and attaches the callback function to the event feed.
1425
+ * @deprecated
1426
+ *
1427
+ * @note the response for the subscription request is issued as a notification event.
1428
+ *
1429
+ * @param {string} method one of the subscribable methods the server supports.
1430
+ * @param {...string} parameters one or more parameters for the method.
1431
+ *
1432
+ * @throws {Error} if not enough clients are connected
1433
+ * @throws {Error} if no response is received with sufficient integrity for the initial request
1434
+ */ async subscribe(method, ...parameters) {
1435
+ // Set up event listener for this subscription.
1436
+ for(const currentClient in this.clients){
1437
+ // Copy the current client for brevity.
1438
+ const client = this.clients[currentClient].connection;
1439
+ try {
1440
+ // Send initial subscription request.
1441
+ // NOTE: This stores and manages the subscription even if the initial request fails.
1442
+ await client.subscribe(method, ...parameters);
1443
+ } catch (error) {
1444
+ // Do nothing, as this is handled on a best-effort basis and
1445
+ // not all servers are expected to be ready at all times.
1446
+ }
1447
+ }
1448
+ }
1449
+ /**
1450
+ * Unsubscribes to the method at the cluster and removes any callback functions
1451
+ * when there are no more subscriptions for the method.
1452
+ * @deprecated
1453
+ *
1454
+ * @param {string} method one of the subscribable methods the server supports.
1455
+ * @param {...string} parameters one or more parameters for the method.
1456
+ *
1457
+ * @throws {Error} if, for any of the clients, no subscriptions exist for the combination of the provided `method` and `parameters.
1458
+ */ async unsubscribe(method, ...parameters) {
1459
+ // Initialize an empty list to track subscription requests.
1460
+ const unsubscriptionPromises = [];
1461
+ // For each client..
1462
+ for(const currentClient in this.clients){
1463
+ // Store client in variable for brevity
1464
+ const client = this.clients[currentClient].connection;
1465
+ // unsubscribe this client.
1466
+ unsubscriptionPromises.push(client.unsubscribe(method, ...parameters));
1467
+ }
1468
+ // Wait for all unsubscription promises to resolve.
1469
+ await Promise.all(unsubscriptionPromises);
1470
+ }
1471
+ /**
1472
+ * Define a callback function to validate server notifications and pass them to the subscribe callback.
1473
+ * @deprecated
1474
+ *
1475
+ * @ignore
1476
+ */ async handleSubscriptionNotifications(clientIdentity, data) {
1477
+ // Lock this response method temporarily.
1478
+ const unlock = await this.responseLock.acquire();
1479
+ try {
1480
+ // Calculate a unique identifier for this notification data.
1481
+ const responseDataIdentifier = (0, $4QiMX$stringify)(data);
1482
+ // Create an empty list of clients who have responded to this notification, if necessary.
1483
+ if (this.notifications[responseDataIdentifier] === undefined) this.notifications[responseDataIdentifier] = new Set();
1484
+ // Ensure this client is on the list of clients that have provided this specific notification.
1485
+ this.notifications[responseDataIdentifier].add(clientIdentity);
1486
+ // Check if this notification has enough integrity according to our confidence strategy.
1487
+ // NOTE: We check against === instead of >== in order to ensure that we only emit each notification once.
1488
+ if (this.notifications[responseDataIdentifier].size === this.confidence) {
1489
+ // Write log entry.
1490
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster(`Validated notification for '${data.method}' with sufficient integrity (${this.confidence}).`);
1491
+ // Emit an event for the notification data.
1492
+ this.emit("notification", data);
1493
+ // Dismiss the notification data after all nodes are assumed to have sent their notifications.
1494
+ // NOTE: This is a redundant mechanic to ensure that even if some nodes don't provide this notification, we still clear this data.
1495
+ // NOTE: This also introduces a race-condition where if a legit identical notification comes in before/during this timeout, it might get silenced.
1496
+ setTimeout(this.dismissSubscriptionNotification.bind(this, responseDataIdentifier), this.timeout);
1497
+ }
1498
+ // Check if this notification has been fully handled.
1499
+ if (this.notifications[responseDataIdentifier].size === this.distribution) // Dismiss existing response data as we know all related parties have provided their input.
1500
+ this.dismissSubscriptionNotification(responseDataIdentifier);
1501
+ } finally{
1502
+ // Unlock the response method so it can handle the next set of data.
1503
+ unlock();
1504
+ }
1505
+ }
1506
+ /**
1507
+ * Forgets/Removes notification data for a specific notification.
1508
+ *
1509
+ * This is required in order to allow future identical notifications to be properly processed and emitted.
1510
+ * @deprecated
1511
+ */ async dismissSubscriptionNotification(responseDataIdentifier) {
1512
+ delete this.notifications[responseDataIdentifier];
1513
+ }
1514
+ /**
1515
+ * Provides a method to check or wait for the cluster to become ready.
1516
+ * @deprecated
1517
+ *
1518
+ * @returns a promise that resolves when the required servers are available.
1519
+ */ async ready() {
1520
+ // Store the current timestamp.
1521
+ const readyTimestamp = Date.now();
1522
+ // Define a function to poll for availability of the cluster.
1523
+ const availabilityPoller = (resolve)=>{
1524
+ // Define a function to check if the cluster is ready to be used.
1525
+ const connectionAvailabilityVerifier = ()=>{
1526
+ // Check if the cluster is active..
1527
+ if (this.status === (0, $a58372b18a18806e$export$c66b56bc0ff967ca).READY) {
1528
+ // Resolve with true to indicate that the cluster is ready to use.
1529
+ resolve(true);
1530
+ // Return after resolving since we do not want to continue the execution.
1531
+ return;
1532
+ }
1533
+ // Calculate how long we have waited, in milliseconds.
1534
+ const timeWaited = Date.now() - readyTimestamp;
1535
+ // Check if we have waited longer than our timeout setting.
1536
+ if (timeWaited > this.timeout) {
1537
+ // Resolve with false to indicate that we did not get ready in time.
1538
+ resolve(false);
1539
+ // Return after resolving since we do not want to continue the execution.
1540
+ return;
1541
+ }
1542
+ // If we are not ready, but have not timed out and should wait more..
1543
+ setTimeout(connectionAvailabilityVerifier, 50);
1544
+ };
1545
+ // Run the initial verification.
1546
+ connectionAvailabilityVerifier();
1547
+ };
1548
+ // Return a promise that resolves when the available clients is sufficient.
1549
+ return new Promise(availabilityPoller);
1550
+ }
1551
+ /**
1552
+ * Connects all servers from the cluster and attaches event listeners and handlers
1553
+ * for all underlying clients and connections.
1554
+ * @deprecated
1555
+ *
1556
+ * @throws {Error} if the cluster's version is not a valid version string.
1557
+ */ async startup() {
1558
+ // Write a log message.
1559
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster("Starting up cluster.");
1560
+ // Keep track of all connections
1561
+ const connections = [];
1562
+ // Loop over all clients and reconnect them if they're disconnected
1563
+ for(const clientKey in this.clients){
1564
+ // Retrieve connection information for the client
1565
+ const { host: host, port: port, scheme: scheme } = this.clients[clientKey].connection.connection;
1566
+ // Only connect currently unavailable/disconnected clients
1567
+ if (this.clients[clientKey].state === (0, $a58372b18a18806e$export$c4f81c6d30ca200f).AVAILABLE) // Warn when a server is already connected when calling startup()
1568
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).warning(`Called startup(), but server ${host}:${port} is already connected`);
1569
+ else // Call the addServer() function with the existing connection data
1570
+ // This effectively reconnects the server and re-instates all event listeners
1571
+ connections.push(this.addServer(host, port, scheme));
1572
+ }
1573
+ // Await all connections
1574
+ return Promise.all(connections);
1575
+ }
1576
+ /**
1577
+ * Disconnects all servers from the cluster. Removes all event listeners and
1578
+ * handlers from all underlying clients and connections. This includes all
1579
+ * active subscriptions, unless retainSubscriptions is set to true.
1580
+ * @deprecated
1581
+ *
1582
+ * @param {boolean} retainSubscriptions retain subscription data so they will be restored on reconnection.
1583
+ *
1584
+ * @returns a list with the disconnection result for every client
1585
+ */ async shutdown(retainSubscriptions = false) {
1586
+ // Write a log message.
1587
+ (0, $ef5ba40c8abe5a13$export$2e2bcd8739ae039).cluster("Shutting down cluster.");
1588
+ // Set up a list of disconnections to wait for.
1589
+ const disconnections = [];
1590
+ const disconnectResolver = (resolve)=>{
1591
+ // Resolve once the cluster is marked as disabled
1592
+ this.once("disabled", ()=>resolve(Promise.all(disconnections)));
1593
+ // For each client in this cluster..
1594
+ for(const clientIndex in this.clients)// Force disconnection regardless of current status.
1595
+ disconnections.push(this.clients[clientIndex].connection.disconnect(true, retainSubscriptions));
1596
+ };
1597
+ // Return a list of booleans indicating disconnections from all clients
1598
+ return new Promise(disconnectResolver);
1599
+ }
1600
+ }
1601
+ var // Export the cluster.
1602
+ $9b2ed2eb52532075$export$2e2bcd8739ae039 = $9b2ed2eb52532075$var$ElectrumCluster;
1603
+
1604
+
1605
+
1606
+
1607
+
1608
+
1609
+
1610
+ export {$620a18299ef8d6fd$export$2e2bcd8739ae039 as ElectrumClient, $9b2ed2eb52532075$export$2e2bcd8739ae039 as ElectrumCluster, $a192ea5a4eec42d4$export$e1f38ab2b4ebdde6 as isVersionRejected, $a192ea5a4eec42d4$export$9598f0c76aa41d73 as isVersionNegotiated, $5abc8fb342687c03$export$d048df559e6d3842 as ElectrumTransport, $5abc8fb342687c03$export$f019be48b3aacb1a as DefaultParameters, $a58372b18a18806e$export$161fe3707f756bf9 as ClusterOrder, $a58372b18a18806e$export$436a960acc41e848 as ClusterDistribution, $a58372b18a18806e$export$c66b56bc0ff967ca as ClusterStatus, $a58372b18a18806e$export$c4f81c6d30ca200f as ClientState, $a58372b18a18806e$export$7516420eb880ab68 as ConnectionStatus};
1611
+ //# sourceMappingURL=index.mjs.map