@electrum-cash/network 4.0.0-development.6620706379 → 4.0.0-development.6620959073

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 DELETED
@@ -1,1265 +0,0 @@
1
- import {EventEmitter as $dvphU$EventEmitter} from "events";
2
- import {Mutex as $dvphU$Mutex} from "async-mutex";
3
- import $dvphU$debug from "debug";
4
- import {parse as $dvphU$parse, parseNumberAndBigInt as $dvphU$parseNumberAndBigInt} from "lossless-json";
5
- import {connect as $dvphU$connect, TLSSocket as $dvphU$TLSSocket} from "tls";
6
- import {isIP as $dvphU$isIP, connect as $dvphU$connect1} from "net";
7
- import {WebSocket as $dvphU$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 $623a31cc1663a627$var$debug = {
16
- client: (0, $dvphU$debug)("electrum-cash:client "),
17
- errors: (0, $dvphU$debug)("electrum-cash:error "),
18
- warning: (0, $dvphU$debug)("electrum-cash:warning"),
19
- network: (0, $dvphU$debug)("electrum-cash:network"),
20
- ping: (0, $dvphU$debug)("electrum-cash:pulses ")
21
- };
22
- // Set log colors.
23
- $623a31cc1663a627$var$debug.client.color = "2";
24
- $623a31cc1663a627$var$debug.errors.color = "9";
25
- $623a31cc1663a627$var$debug.warning.color = "13";
26
- $623a31cc1663a627$var$debug.network.color = "4";
27
- $623a31cc1663a627$var$debug.ping.color = "8";
28
- var // Export the logs.
29
- $623a31cc1663a627$export$2e2bcd8739ae039 = $623a31cc1663a627$var$debug;
30
-
31
-
32
-
33
- /**
34
- * Grouping of utilities that simplifies implementation of the Electrum protocol.
35
- *
36
- * @ignore
37
- */ class $24139611f53a54b8$var$ElectrumProtocol {
38
- /**
39
- * Helper function that builds an Electrum request object.
40
- *
41
- * @param {string} method method to call.
42
- * @param {array} parameters method parameters for the call.
43
- * @param {string} requestId unique string or number referencing this request.
44
- *
45
- * @returns a properly formatted Electrum request string.
46
- */ static buildRequestObject(method, parameters, requestId) {
47
- // Return the formatted request object.
48
- // NOTE: Electrum either uses JsonRPC strictly or loosely.
49
- // If we specify protocol identifier without being 100% compliant, we risk being disconnected/blacklisted.
50
- // For this reason, we omit the protocol identifier to avoid issues.
51
- return JSON.stringify({
52
- method: method,
53
- params: parameters,
54
- id: requestId
55
- });
56
- }
57
- /**
58
- * Constant used to verify if a provided string is a valid version number.
59
- *
60
- * @returns a regular expression that matches valid version numbers.
61
- */ static get versionRegexp() {
62
- return /^\d+(\.\d+)+$/;
63
- }
64
- /**
65
- * Constant used to separate statements/messages in a stream of data.
66
- *
67
- * @returns the delimiter used by Electrum to separate statements.
68
- */ static get statementDelimiter() {
69
- return "\n";
70
- }
71
- }
72
- var // export the protocol.
73
- $24139611f53a54b8$export$2e2bcd8739ae039 = $24139611f53a54b8$var$ElectrumProtocol;
74
-
75
-
76
- var $e83d2e7688025acd$exports = {};
77
-
78
- $parcel$export($e83d2e7688025acd$exports, "isVersionRejected", () => $e83d2e7688025acd$export$e1f38ab2b4ebdde6);
79
- $parcel$export($e83d2e7688025acd$exports, "isVersionNegotiated", () => $e83d2e7688025acd$export$9598f0c76aa41d73);
80
- const $e83d2e7688025acd$export$e1f38ab2b4ebdde6 = function(object) {
81
- return "error" in object;
82
- };
83
- const $e83d2e7688025acd$export$9598f0c76aa41d73 = function(object) {
84
- return "software" in object && "protocol" in object;
85
- };
86
-
87
-
88
- var $d801b1f9b7fc3074$exports = {};
89
-
90
- $parcel$export($d801b1f9b7fc3074$exports, "ElectrumTransport", () => $d801b1f9b7fc3074$export$d048df559e6d3842);
91
- $parcel$export($d801b1f9b7fc3074$exports, "DefaultParameters", () => $d801b1f9b7fc3074$export$f019be48b3aacb1a);
92
- const $d801b1f9b7fc3074$export$d048df559e6d3842 = {
93
- TCP: {
94
- Port: 50001,
95
- Scheme: "tcp"
96
- },
97
- TCP_TLS: {
98
- Port: 50002,
99
- Scheme: "tcp_tls"
100
- },
101
- WS: {
102
- Port: 50003,
103
- Scheme: "ws"
104
- },
105
- WSS: {
106
- Port: 50004,
107
- Scheme: "wss"
108
- }
109
- };
110
- const $d801b1f9b7fc3074$export$f019be48b3aacb1a = {
111
- // Port number for TCP TLS connections
112
- PORT: $d801b1f9b7fc3074$export$d048df559e6d3842.TCP_TLS.Port,
113
- // Transport to connect to the Electrum server
114
- TRANSPORT_SCHEME: $d801b1f9b7fc3074$export$d048df559e6d3842.TCP_TLS.Scheme,
115
- // How long to wait before attempting to reconnect, in milliseconds.
116
- RECONNECT: 5000,
117
- // How long to wait for network operations before following up, in milliseconds.
118
- TIMEOUT: 30000,
119
- // Time between ping messages, in milliseconds. Pinging keeps the connection alive.
120
- // The reason for pinging this frequently is to detect connection problems early.
121
- PING_INTERVAL: 1000,
122
- // If we use BigInt for numbers in json when parsing and returning json response from the server.
123
- USE_BIG_INT: false
124
- };
125
-
126
-
127
-
128
-
129
-
130
-
131
-
132
-
133
-
134
- class $0a4cf22b9d6c493c$export$22c0ca2c816c3e08 extends (0, $dvphU$EventEmitter) {
135
- /**
136
- * Connect to host:port using the specified transport
137
- *
138
- * @param {string} host Fully qualified domain name or IP address of the host
139
- * @param {number} port Network port for the host to connect to
140
- * @param {TransportScheme} scheme Transport scheme to use
141
- * @param {number} timeout If no connection is established after `timeout` ms, the connection is terminated
142
- *
143
- * @throws {Error} if an incorrect transport scheme is specified
144
- */ connect(host, port, scheme, timeout) {
145
- // Check that no existing socket exists before initiating a new connection.
146
- if (this.tcpSocket) throw new Error("Cannot initiate a new socket connection when an existing connection exists");
147
- // Set a timer to force disconnect after `timeout` seconds
148
- this.timers.disconnect = setTimeout(()=>this.disconnectOnTimeout(host, port, timeout), timeout);
149
- // Remove the timer if a connection is successfully established
150
- this.once("connect", this.clearDisconnectTimerOnTimeout);
151
- // Define how to refer to the connection scheme in debug output.
152
- const socketTypes = {
153
- [(0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP.Scheme]: "a TCP Socket",
154
- [(0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP_TLS.Scheme]: "an encrypted TCP socket"
155
- };
156
- // Log that we are trying to establish a connection.
157
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Initiating ${socketTypes[scheme]} connection to '${host}:${port}'.`);
158
- if (scheme !== (0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP.Scheme && scheme !== (0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP_TLS.Scheme) // Throw an error if an incorrect transport is specified
159
- throw new Error("Incorrect transport specified");
160
- if (scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP_TLS.Scheme) {
161
- // Initialize connection options.
162
- const connectionOptions = {
163
- rejectUnauthorized: false
164
- };
165
- // If the hostname is not an IP address..
166
- if (!$dvphU$isIP(host)) // Set the servername option which enables support for SNI.
167
- // NOTE: SNI enables a server that hosts multiple domains to provide the appropriate TLS certificate.
168
- connectionOptions.serverName = host;
169
- // Initialize the socket (allowing self-signed certificates).
170
- this.tcpSocket = $dvphU$connect(port, host, connectionOptions);
171
- // Add a 'secureConnect' listener that checks the authorization status of
172
- // the socket, and logs a warning when it uses a self signed certificate.
173
- this.tcpSocket.once("secureConnect", ()=>{
174
- // Cannot happen, since this event callback *only* exists on TLSSocket
175
- if (!(this.tcpSocket instanceof $dvphU$TLSSocket)) return;
176
- // Force cast authorizationError from Error to string (through unknown)
177
- // because it is incorrectly typed as an Error
178
- const authorizationError = this.tcpSocket.authorizationError;
179
- if (authorizationError === "DEPTH_ZERO_SELF_SIGNED_CERT") (0, $623a31cc1663a627$export$2e2bcd8739ae039).warning(`Connection to ${host}:${port} uses a self-signed certificate`);
180
- });
181
- // Trigger successful connection events.
182
- this.tcpSocket.on("secureConnect", this.onConnect.bind(this, socketTypes[scheme], host, port));
183
- } else {
184
- // Initialize the socket.
185
- this.tcpSocket = $dvphU$connect1({
186
- host: host,
187
- port: port
188
- });
189
- // Trigger successful connection events.
190
- this.tcpSocket.on("connect", this.onConnect.bind(this, socketTypes[scheme], host, port));
191
- }
192
- // Configure encoding.
193
- this.tcpSocket.setEncoding("utf8");
194
- // Enable persistent connections.
195
- // NOTE: This will send a non-data message 0.25 second after last activity.
196
- // After 10 consecutive such messages with no response, the connection will be cut.
197
- this.tcpSocket.setKeepAlive(true, 250);
198
- // Disable buffering of outgoing data.
199
- this.tcpSocket.setNoDelay(true);
200
- // Forward the encountered errors.
201
- this.tcpSocket.on("error", this.eventForwarders.tcpError);
202
- }
203
- /**
204
- * Sets up forwarding of events related to the connection.
205
- *
206
- * @param {string} connectionType Name of the connection/transport type, used for logging.
207
- * @param {string} host Fully qualified domain name or IP address of the host
208
- * @param {number} port Network port for the host to connect to
209
- */ onConnect(connectionType, host, port) {
210
- // If the onConnect function has already run, do not execute it again.
211
- if (this.onConnectHasRun) return;
212
- // Log that the connection has been established.
213
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Established ${connectionType} connection with '${host}:${port}'.`);
214
- // Forward the socket events
215
- this.tcpSocket.addListener("close", this.eventForwarders.disconnect);
216
- this.tcpSocket.addListener("data", this.eventForwarders.tcpData);
217
- // Indicate that the onConnect function has run.
218
- this.onConnectHasRun = true;
219
- // Emit the connect event.
220
- this.emit("connect");
221
- }
222
- /**
223
- * Clears the disconnect timer if it is still active.
224
- */ clearDisconnectTimerOnTimeout() {
225
- // Clear the retry timer if it is still active.
226
- if (this.timers.disconnect) clearTimeout(this.timers.disconnect);
227
- }
228
- /**
229
- * Forcibly terminate the connection.
230
- *
231
- * @throws {Error} if no connection was found
232
- */ disconnect() {
233
- // Clear the disconnect timer so that the socket does not try to disconnect again later.
234
- this.clearDisconnectTimerOnTimeout();
235
- if (this.tcpSocket) {
236
- // Remove all event forwarders.
237
- this.tcpSocket.removeListener("close", this.eventForwarders.disconnect);
238
- this.tcpSocket.removeListener("data", this.eventForwarders.tcpData);
239
- this.tcpSocket.removeListener("error", this.eventForwarders.tcpError);
240
- // Terminate the connection.
241
- this.tcpSocket.destroy();
242
- // Remove the stored socket.
243
- this.tcpSocket = undefined;
244
- }
245
- // Indicate that the onConnect function has not run and it has to be run again.
246
- this.onConnectHasRun = false;
247
- // Emit a disconnect event
248
- this.emit("disconnect");
249
- }
250
- /**
251
- * Write data to the socket
252
- *
253
- * @param {Uint8Array | string} data Data to be written to the socket
254
- * @param {function} callback Callback function to be called when the write has completed
255
- *
256
- * @throws {Error} if no connection was found
257
- * @returns true if the message was fully flushed to the socket, false if part of the message
258
- * is queued in the user memory
259
- */ write(data, callback) {
260
- // Throw an error if no active connection is found
261
- if (!this.tcpSocket) throw new Error("Cannot write to socket when there is no active connection");
262
- // Write data to the TLS Socket and return the status indicating
263
- // whether the full message was flushed to the socket
264
- return this.tcpSocket.write(data, callback);
265
- }
266
- /**
267
- * Force a disconnection if no connection is established after `timeout` milliseconds.
268
- *
269
- * @param {string} host Host of the connection that timed out
270
- * @param {number} port Port of the connection that timed out
271
- * @param {number} timeout Elapsed milliseconds
272
- */ disconnectOnTimeout(host, port, timeout) {
273
- // Remove the connect listener.
274
- this.removeListener("connect", this.clearDisconnectTimerOnTimeout);
275
- // Create a new timeout error.
276
- const timeoutError = {
277
- code: "ETIMEDOUT",
278
- message: `Connection to '${host}:${port}' timed out after ${timeout} milliseconds`
279
- };
280
- // Emit an error event so that connect is rejected upstream.
281
- this.emit("error", timeoutError);
282
- // Forcibly disconnect to clean up the connection on timeout
283
- this.disconnect();
284
- }
285
- constructor(...args){
286
- super(...args);
287
- // Declare timers for keep-alive pings and reconnection
288
- this.timers = {};
289
- // Initialize boolean that indicates whether the onConnect function has run (initialize to false).
290
- this.onConnectHasRun = false;
291
- // Initialize event forwarding functions.
292
- this.eventForwarders = {
293
- disconnect: ()=>this.emit("disconnect"),
294
- tcpData: (data)=>this.emit("data", data),
295
- tcpError: (err)=>this.emit("error", err)
296
- };
297
- }
298
- }
299
- class $0a4cf22b9d6c493c$export$25b4633f61498e1 extends (0, $dvphU$EventEmitter) {
300
- /**
301
- * Connect to host:port using the specified transport
302
- *
303
- * @param {string} host Fully qualified domain name or IP address of the host
304
- * @param {number} port Network port for the host to connect to
305
- * @param {TransportScheme} scheme Transport scheme to use
306
- * @param {number} timeout If no connection is established after `timeout` ms, the connection is terminated
307
- *
308
- * @throws {Error} if an incorrect transport scheme is specified
309
- */ connect(host, port, scheme, timeout) {
310
- // Check that no existing socket exists before initiating a new connection.
311
- if (this.webSocket) throw new Error("Cannot initiate a new socket connection when an existing connection exists");
312
- // Set a timer to force disconnect after `timeout` seconds
313
- this.timers.disconnect = setTimeout(()=>this.disconnectOnTimeout(host, port, timeout), timeout);
314
- // Remove the timer if a connection is successfully established
315
- this.once("connect", this.clearDisconnectTimerOnTimeout);
316
- // Define how to refer to the connection scheme in debug output.
317
- const socketTypes = {
318
- [(0, $d801b1f9b7fc3074$export$d048df559e6d3842).WS.Scheme]: "a WebSocket",
319
- [(0, $d801b1f9b7fc3074$export$d048df559e6d3842).WSS.Scheme]: "an encrypted WebSocket"
320
- };
321
- // Log that we are trying to establish a connection.
322
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Initiating ${socketTypes[scheme]} connection to '${host}:${port}'.`);
323
- if (scheme !== (0, $d801b1f9b7fc3074$export$d048df559e6d3842).WS.Scheme && scheme !== (0, $d801b1f9b7fc3074$export$d048df559e6d3842).WSS.Scheme) // Throw an error if an incorrect transport is specified
324
- throw new Error("Incorrect transport specified");
325
- if (scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).WSS.Scheme) // Initialize this.webSocket (rejecting self-signed certificates).
326
- // We reject self-signed certificates to match functionality of browsers.
327
- this.webSocket = new (0, $dvphU$WebSocket)(`wss://${host}:${port}`);
328
- else // Initialize this.webSocket.
329
- this.webSocket = new (0, $dvphU$WebSocket)(`ws://${host}:${port}`);
330
- // Trigger successful connection events.
331
- this.webSocket.addEventListener("open", this.onConnect.bind(this, socketTypes[scheme], host, port));
332
- // Forward the encountered errors.
333
- this.webSocket.addEventListener("error", this.eventForwarders.wsError);
334
- }
335
- /**
336
- * Sets up forwarding of events related to the connection.
337
- *
338
- * @param {string} connectionType Name of the connection/transport type, used for logging.
339
- * @param {string} host Fully qualified domain name or IP address of the host
340
- * @param {number} port Network port for the host to connect to
341
- */ onConnect(connectionType, host, port) {
342
- // If the onConnect function has already run, do not execute it again.
343
- if (this.onConnectHasRun) return;
344
- // Log that the connection has been established.
345
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Established ${connectionType} connection with '${host}:${port}'.`);
346
- // Forward the socket events
347
- this.webSocket.addEventListener("close", this.eventForwarders.disconnect);
348
- this.webSocket.addEventListener("message", this.eventForwarders.wsData);
349
- // Indicate that the onConnect function has run.
350
- this.onConnectHasRun = true;
351
- // Emit the connect event.
352
- this.emit("connect");
353
- }
354
- /**
355
- * Clears the disconnect timer if it is still active.
356
- */ clearDisconnectTimerOnTimeout() {
357
- // Clear the retry timer if it is still active.
358
- if (this.timers.disconnect) clearTimeout(this.timers.disconnect);
359
- }
360
- /**
361
- * Forcibly terminate the connection.
362
- *
363
- * @throws {Error} if no connection was found
364
- */ disconnect() {
365
- // Clear the disconnect timer so that the socket does not try to disconnect again later.
366
- this.clearDisconnectTimerOnTimeout();
367
- try {
368
- // Remove all event forwarders.
369
- this.webSocket.removeEventListener("close", this.eventForwarders.disconnect);
370
- this.webSocket.removeEventListener("message", this.eventForwarders.wsData);
371
- this.webSocket.removeEventListener("error", this.eventForwarders.wsError);
372
- // Gracefully terminate the connection.
373
- this.webSocket.close();
374
- } catch (ignored) {
375
- // close() will throw an error if the connection has not been established yet.
376
- // We ignore this error, since no similar error gets thrown in the TLS Socket.
377
- } finally{
378
- // Remove the stored socket regardless of any thrown errors.
379
- this.webSocket = undefined;
380
- }
381
- // Indicate that the onConnect function has not run and it has to be run again.
382
- this.onConnectHasRun = false;
383
- // Emit a disconnect event
384
- this.emit("disconnect");
385
- }
386
- /**
387
- * Write data to the socket
388
- *
389
- * @param {Uint8Array | string} data Data to be written to the socket
390
- * @param {function} callback Callback function to be called when the write has completed
391
- *
392
- * @throws {Error} if no connection was found
393
- * @returns true if the message was fully flushed to the socket, false if part of the message
394
- * is queued in the user memory
395
- */ write(data, callback) {
396
- // Throw an error if no active connection is found
397
- if (!this.webSocket) throw new Error("Cannot write to socket when there is no active connection");
398
- // Write data to the WebSocket
399
- this.webSocket.send(data, callback);
400
- // WebSockets always fit everything in a single request, so we return true
401
- return true;
402
- }
403
- /**
404
- * Force a disconnection if no connection is established after `timeout` milliseconds.
405
- *
406
- * @param {string} host Host of the connection that timed out
407
- * @param {number} port Port of the connection that timed out
408
- * @param {number} timeout Elapsed milliseconds
409
- */ disconnectOnTimeout(host, port, timeout) {
410
- // Remove the connect listener.
411
- this.removeListener("connect", this.clearDisconnectTimerOnTimeout);
412
- // Create a new timeout error.
413
- const timeoutError = {
414
- code: "ETIMEDOUT",
415
- message: `Connection to '${host}:${port}' timed out after ${timeout} milliseconds`
416
- };
417
- // Emit an error event so that connect is rejected upstream.
418
- this.emit("error", timeoutError);
419
- // Forcibly disconnect to clean up the connection on timeout
420
- this.disconnect();
421
- }
422
- constructor(...args){
423
- super(...args);
424
- // Declare timers for keep-alive pings and reconnection
425
- this.timers = {};
426
- // Initialize boolean that indicates whether the onConnect function has run (initialize to false).
427
- this.onConnectHasRun = false;
428
- // Initialize event forwarding functions.
429
- this.eventForwarders = {
430
- disconnect: ()=>this.emit("disconnect"),
431
- wsData: (event)=>this.emit("data", `${event.data}\n`),
432
- wsError: (event)=>this.emit("error", event.error)
433
- };
434
- }
435
- }
436
-
437
-
438
- var $db7c797e63383364$exports = {};
439
-
440
- $parcel$export($db7c797e63383364$exports, "ClientState", () => $db7c797e63383364$export$c4f81c6d30ca200f);
441
- $parcel$export($db7c797e63383364$exports, "ConnectionStatus", () => $db7c797e63383364$export$7516420eb880ab68);
442
- // Disable indent rule for this file because it is broken (https://github.com/typescript-eslint/typescript-eslint/issues/1824)
443
- /* eslint-disable @typescript-eslint/indent */ /**
444
- * Enum that denotes the availability of an ElectrumClient.
445
- * @enum {number}
446
- * @property {0} UNAVAILABLE The client is currently not available.
447
- * @property {1} AVAILABLE The client is available for use.
448
- */ var $db7c797e63383364$export$c4f81c6d30ca200f;
449
- (function(ClientState) {
450
- ClientState[ClientState["UNAVAILABLE"] = 0] = "UNAVAILABLE";
451
- ClientState[ClientState["AVAILABLE"] = 1] = "AVAILABLE";
452
- })($db7c797e63383364$export$c4f81c6d30ca200f || ($db7c797e63383364$export$c4f81c6d30ca200f = {}));
453
- var $db7c797e63383364$export$7516420eb880ab68;
454
- (function(ConnectionStatus) {
455
- ConnectionStatus[ConnectionStatus["DISCONNECTED"] = 0] = "DISCONNECTED";
456
- ConnectionStatus[ConnectionStatus["CONNECTED"] = 1] = "CONNECTED";
457
- ConnectionStatus[ConnectionStatus["DISCONNECTING"] = 2] = "DISCONNECTING";
458
- ConnectionStatus[ConnectionStatus["CONNECTING"] = 3] = "CONNECTING";
459
- ConnectionStatus[ConnectionStatus["RECONNECTING"] = 4] = "RECONNECTING";
460
- })($db7c797e63383364$export$7516420eb880ab68 || ($db7c797e63383364$export$7516420eb880ab68 = {}));
461
-
462
-
463
-
464
- /**
465
- * Wrapper around TLS/WSS sockets that gracefully separates a network stream into Electrum protocol messages.
466
- */ class $ff134c9a9e1f7361$var$ElectrumConnection extends (0, $dvphU$EventEmitter) {
467
- /**
468
- * Sets up network configuration for an Electrum client connection.
469
- *
470
- * @param {string} application your application name, used to identify to the electrum host.
471
- * @param {string} version protocol version to use with the host.
472
- * @param {string} host fully qualified domain name or IP number of the host.
473
- * @param {number} port the network port of the host.
474
- * @param {TransportScheme} scheme the transport scheme to use for connection
475
- * @param {number} timeout how long network delays we will wait for before taking action, in milliseconds.
476
- * @param {number} pingInterval the time between sending pings to the electrum host, in milliseconds.
477
- * @param {number} reconnectInterval the time between reconnection attempts to the electrum host, in milliseconds.
478
- * @param {boolean} useBigInt whether to use bigint for numbers in json response.
479
- *
480
- * @throws {Error} if `version` is not a valid version string.
481
- */ constructor(application, version, host, port = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).PORT, scheme = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).TRANSPORT_SCHEME, timeout = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).TIMEOUT, pingInterval = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).PING_INTERVAL, reconnectInterval = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).RECONNECT, useBigInt = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).USE_BIG_INT){
482
- // Initialize the event emitter.
483
- super();
484
- this.application = application;
485
- this.version = version;
486
- this.host = host;
487
- this.port = port;
488
- this.scheme = scheme;
489
- this.timeout = timeout;
490
- this.pingInterval = pingInterval;
491
- this.reconnectInterval = reconnectInterval;
492
- this.useBigInt = useBigInt;
493
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;
494
- this.timers = {};
495
- this.verifications = [];
496
- this.messageBuffer = "";
497
- // Check if the provided version is a valid version number.
498
- if (!(0, $24139611f53a54b8$export$2e2bcd8739ae039).versionRegexp.test(version)) // Throw an error since the version number was not valid.
499
- throw new Error(`Provided version string (${version}) is not a valid protocol version number.`);
500
- // Create an initial network socket.
501
- this.createSocket();
502
- // Handle visibility changes when run in a browser environment.
503
- if (typeof document !== "undefined") document.addEventListener("visibilitychange", this.handleVisibilityChange.bind(this));
504
- // Handle network connection changes when run in a browser environment.
505
- if (typeof window !== "undefined") {
506
- window.addEventListener("online", this.handleNetworkChange.bind(this));
507
- window.addEventListener("offline", this.handleNetworkChange.bind(this));
508
- }
509
- }
510
- /**
511
- * Returns a string for the host identifier for usage in debug messages.
512
- */ get hostIdentifier() {
513
- return `${this.host}:${this.port}`;
514
- }
515
- /**
516
- * Create and configures a fresh socket and attaches all relevant listeners.
517
- */ createSocket() {
518
- if (this.scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP.Scheme || this.scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).TCP_TLS.Scheme) // Initialize a new ElectrumTcpSocket
519
- this.socket = new (0, $0a4cf22b9d6c493c$export$22c0ca2c816c3e08)();
520
- else if (this.scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).WS.Scheme || this.scheme === (0, $d801b1f9b7fc3074$export$d048df559e6d3842).WSS.Scheme) // Initialize a new ElectrumWebSocket
521
- this.socket = new (0, $0a4cf22b9d6c493c$export$25b4633f61498e1)();
522
- else // Throw an error if an incorrect transport is specified
523
- throw new Error(`Provided transport (${this.scheme}) is not a valid ElectrumTransport`);
524
- // Set up handlers for connection and disconnection.
525
- this.socket.on("connect", this.onSocketConnect.bind(this));
526
- this.socket.on("disconnect", this.onSocketDisconnect.bind(this));
527
- // Set up handler for incoming data.
528
- this.socket.on("data", this.parseMessageChunk.bind(this));
529
- }
530
- /**
531
- * Shuts down and destroys the current socket.
532
- */ destroySocket() {
533
- // Close the socket connection and destroy the socket.
534
- this.socket.disconnect();
535
- }
536
- /**
537
- * Assembles incoming data into statements and hands them off to the message parser.
538
- *
539
- * @param {string} data data to append to the current message buffer, as a string.
540
- *
541
- * @throws {SyntaxError} if the passed statement parts are not valid JSON.
542
- */ parseMessageChunk(data) {
543
- // Update the timestamp for when we last received data.
544
- this.lastReceivedTimestamp = Date.now();
545
- // Emit a notification indicating that the connection has received data.
546
- this.emit("received");
547
- // Clear and remove all verification timers.
548
- this.verifications.forEach((timer)=>clearTimeout(timer));
549
- this.verifications.length = 0;
550
- // Add the message to the current message buffer.
551
- this.messageBuffer += data;
552
- // Check if the new message buffer contains the statement delimiter.
553
- while(this.messageBuffer.includes((0, $24139611f53a54b8$export$2e2bcd8739ae039).statementDelimiter)){
554
- // Split message buffer into statements.
555
- const statementParts = this.messageBuffer.split((0, $24139611f53a54b8$export$2e2bcd8739ae039).statementDelimiter);
556
- // For as long as we still have statements to parse..
557
- while(statementParts.length > 1){
558
- // Move the first statement to its own variable.
559
- const currentStatementList = String(statementParts.shift());
560
- // Parse the statement into an object or list of objects.
561
- let statementList = (0, $dvphU$parse)(currentStatementList, null, this.useBigInt ? (0, $dvphU$parseNumberAndBigInt) : parseFloat);
562
- // Wrap the statement in an array if it is not already a batched statement list.
563
- if (!Array.isArray(statementList)) statementList = [
564
- statementList
565
- ];
566
- // For as long as there is statements in the result set..
567
- while(statementList.length > 0){
568
- // Move the first statement from the batch to its own variable.
569
- const currentStatement = statementList.shift();
570
- // If the current statement is a version negotiation response..
571
- if (currentStatement.id === "versionNegotiation") {
572
- if (currentStatement.error) // Then emit a failed version negotiation response signal.
573
- this.emit("version", {
574
- error: currentStatement.error
575
- });
576
- else {
577
- // Extract the software and protocol version reported.
578
- const [software, protocol] = currentStatement.result;
579
- // Emit a successful version negotiation response signal.
580
- this.emit("version", {
581
- software: software,
582
- protocol: protocol
583
- });
584
- }
585
- continue;
586
- }
587
- // If the current statement is a keep-alive response..
588
- if (currentStatement.id === "keepAlive") continue;
589
- // Emit the statements for handling higher up in the stack.
590
- this.emit("statement", currentStatement);
591
- }
592
- }
593
- // Store the remaining statement as the current message buffer.
594
- this.messageBuffer = statementParts.shift() || "";
595
- }
596
- }
597
- /**
598
- * Sends a keep-alive message to the host.
599
- *
600
- * @returns true if the ping message was fully flushed to the socket, false if
601
- * part of the message is queued in the user memory
602
- */ ping() {
603
- // Write a log message.
604
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).ping(`Sending keep-alive ping to '${this.hostIdentifier}'`);
605
- // Craft a keep-alive message.
606
- const message = (0, $24139611f53a54b8$export$2e2bcd8739ae039).buildRequestObject("server.ping", [], "keepAlive");
607
- // Send the keep-alive message.
608
- const status = this.send(message);
609
- // Return the ping status.
610
- return status;
611
- }
612
- /**
613
- * Initiates the network connection negotiates a protocol version. Also emits the 'connect' signal if successful.
614
- *
615
- * @throws {Error} if the socket connection fails.
616
- * @returns a promise resolving when the connection is established
617
- */ async connect() {
618
- // If we are already connected return true.
619
- if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) return;
620
- // Indicate that the connection is connecting
621
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTING;
622
- // Define a function to wrap connection as a promise.
623
- const connectionResolver = (resolve, reject)=>{
624
- const rejector = (error)=>{
625
- // Set the status back to disconnected
626
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;
627
- // Reject with the error as reason
628
- reject(error);
629
- };
630
- // Replace previous error handlers to reject the promise on failure.
631
- this.socket.removeAllListeners("error");
632
- this.socket.once("error", rejector);
633
- // Define a function to wrap version negotiation as a callback.
634
- const versionNegotiator = ()=>{
635
- // Write a log message to show that we have started version negotiation.
636
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Requesting protocol version ${this.version} with '${this.hostIdentifier}'.`);
637
- // remove the one-time error handler since no error was detected.
638
- this.socket.removeListener("error", rejector);
639
- // Build a version negotiation message.
640
- const versionMessage = (0, $24139611f53a54b8$export$2e2bcd8739ae039).buildRequestObject("server.version", [
641
- this.application,
642
- this.version
643
- ], "versionNegotiation");
644
- // Define a function to wrap version validation as a function.
645
- const versionValidator = (version)=>{
646
- // Check if version negotiation failed.
647
- if ((0, $e83d2e7688025acd$export$e1f38ab2b4ebdde6)(version)) {
648
- // Disconnect from the host.
649
- this.disconnect(true);
650
- // Declare an error message.
651
- const errorMessage = "unsupported protocol version.";
652
- // Log the error.
653
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);
654
- // Reject the connection with false since version negotiation failed.
655
- reject(errorMessage);
656
- } else if (version.protocol !== this.version && `${version.protocol}.0` !== this.version && `${version.protocol}.0.0` !== this.version) {
657
- // Disconnect from the host.
658
- this.disconnect(true);
659
- // Declare an error message.
660
- const errorMessage = `incompatible protocol version negotiated (${version.protocol} !== ${this.version}).`;
661
- // Log the error.
662
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(`Failed to connect with ${this.hostIdentifier} due to ${errorMessage}`);
663
- // Reject the connection with false since version negotiation failed.
664
- reject(errorMessage);
665
- } else {
666
- // Write a log message.
667
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Negotiated protocol version ${version.protocol} with '${this.hostIdentifier}', powered by ${version.software}.`);
668
- // Set connection status to connected
669
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED;
670
- // Emit a connect event now that the connection is usable.
671
- this.emit("connect");
672
- // Resolve the connection promise since we successfully connected and negotiated protocol version.
673
- resolve();
674
- }
675
- };
676
- // Listen for version negotiation once.
677
- this.once("version", versionValidator);
678
- // Send the version negotiation message.
679
- this.send(versionMessage);
680
- };
681
- // Prepare the version negotiation.
682
- this.socket.once("connect", versionNegotiator);
683
- // Set up handler for network errors.
684
- this.socket.on("error", this.onSocketError.bind(this));
685
- // Connect to the server.
686
- this.socket.connect(this.host, this.port, this.scheme, this.timeout);
687
- };
688
- // Wait until connection is established and version negotiation succeeds.
689
- await new Promise(connectionResolver);
690
- }
691
- /**
692
- * Restores the network connection.
693
- */ async reconnect() {
694
- // If a reconnect timer is set, remove it
695
- await this.clearReconnectTimer();
696
- // Write a log message.
697
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Trying to reconnect to '${this.hostIdentifier}'..`);
698
- // Set the status to reconnecting for more accurate log messages.
699
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).RECONNECTING;
700
- // Destroy and recreate the socket to get a clean slate.
701
- this.destroySocket();
702
- this.createSocket();
703
- try {
704
- // Try to connect again.
705
- await this.connect();
706
- } catch (error) {
707
- // Do nothing as the error should be handled via the disconnect and error signals.
708
- }
709
- }
710
- /**
711
- * Removes the current reconnect timer.
712
- */ clearReconnectTimer() {
713
- // If a reconnect timer is set, remove it
714
- if (this.timers.reconnect) clearTimeout(this.timers.reconnect);
715
- // Reset the timer reference.
716
- this.timers.reconnect = undefined;
717
- }
718
- /**
719
- * Removes the current keep-alive timer.
720
- */ clearKeepAliveTimer() {
721
- // If a keep-alive timer is set, remove it
722
- if (this.timers.keepAlive) clearTimeout(this.timers.keepAlive);
723
- // Reset the timer reference.
724
- this.timers.keepAlive = undefined;
725
- }
726
- /**
727
- * Initializes the keep alive timer loop.
728
- */ setupKeepAliveTimer() {
729
- // If the keep-alive timer loop is not currently set up..
730
- if (!this.timers.keepAlive) // Set a new keep-alive timer.
731
- this.timers.keepAlive = setTimeout(this.ping.bind(this), this.pingInterval);
732
- }
733
- /**
734
- * Tears down the current connection and removes all event listeners on disconnect.
735
- *
736
- * @param {boolean} force disconnect even if the connection has not been fully established yet.
737
- * @param {boolean} intentional update connection state if disconnect is intentional.
738
- *
739
- * @returns true if successfully disconnected, or false if there was no connection.
740
- */ async disconnect(force = false, intentional = true) {
741
- // Return early when there is nothing to disconnect from
742
- if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED && !force) // Return false to indicate that there was nothing to disconnect from.
743
- return false;
744
- // Update connection state if the disconnection is intentional.
745
- // NOTE: The state is meant to represent what the client is requesting, but
746
- // is used internally to handle visibility changes in browsers to ensure functional reconnection.
747
- if (intentional) // Set connection status to null to indicate tear-down is currently happening.
748
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING;
749
- // If a keep-alive timer is set, remove it.
750
- await this.clearKeepAliveTimer();
751
- // If a reconnect timer is set, remove it
752
- await this.clearReconnectTimer();
753
- const disconnectResolver = (resolve)=>{
754
- // Resolve to true after the connection emits a disconnect
755
- this.once("disconnect", ()=>resolve(true));
756
- // Close the connection and destroy the socket.
757
- this.destroySocket();
758
- };
759
- // Return true to indicate that we disconnected.
760
- return new Promise(disconnectResolver);
761
- }
762
- /**
763
- * TODO: Use
764
- */ async handleNetworkChange() {
765
- // Do nothing if we do not have the navigator available.
766
- if (typeof navigator === "undefined") return;
767
- // Do nothing if we might still be online.
768
- // NOTE: we check for not-false here since true does not mean that we are connected to the internet,
769
- // but rather that the browser believes there is an active network connection of any type.
770
- if (window.navigator.onLine !== false) return;
771
- // Disconnect without signalling intent, to trigger automatic recovery routines.
772
- this.disconnect(false, false);
773
- }
774
- /**
775
- * Updates connection state based on application visibility.
776
- *
777
- * Some browsers will disconnect network connections when the browser is out of focus,
778
- * which would normally cause our reconnect-on-timeout routines to trigger, but that
779
- * results in a poor user experience since the events are not handled consistently
780
- * and sometimes it can take some time after restoring focus to the browser.
781
- *
782
- * By manually disconnecting when this happens we prevent the default reconnection routines
783
- * and make the behavior consistent across browsers.
784
- */ async handleVisibilityChange() {
785
- // Disconnect when application is removed from focus.
786
- if (document.visibilityState === "hidden") {
787
- const forceDisconnect = true;
788
- const isIntended = false;
789
- this.disconnect(forceDisconnect, isIntended);
790
- }
791
- // Reconnect when application is returned to focus.
792
- if (document.visibilityState === "visible") this.reconnect();
793
- }
794
- /**
795
- * Sends an arbitrary message to the server.
796
- *
797
- * @param {string} message json encoded request object to send to the server, as a string.
798
- *
799
- * @returns true if the message was fully flushed to the socket, false if part of the message
800
- * is queued in the user memory
801
- */ send(message) {
802
- // Remove the current keep-alive timer if it exists.
803
- this.clearKeepAliveTimer();
804
- // Get the current timestamp in milliseconds.
805
- const currentTime = Date.now();
806
- // Follow up and verify that the message got sent..
807
- const verificationTimer = setTimeout(this.verifySend.bind(this, currentTime), this.timeout);
808
- // Store the verification timer locally so that it can be cleared when data has been received.
809
- this.verifications.push(verificationTimer);
810
- // Set a new keep-alive timer.
811
- this.setupKeepAliveTimer();
812
- // Write the message to the network socket.
813
- return this.socket.write(message + (0, $24139611f53a54b8$export$2e2bcd8739ae039).statementDelimiter);
814
- }
815
- // --- Event managers. --- //
816
- /**
817
- * Marks the connection as timed out and schedules reconnection if we have not
818
- * received data within the expected time frame.
819
- */ verifySend(sentTimestamp) {
820
- // If we haven't received any data since we last sent data out..
821
- if (Number(this.lastReceivedTimestamp) < sentTimestamp) {
822
- // If this connection is already disconnected, we do not change anything
823
- if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED || this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING) // debug.warning(`Tried to verify already disconnected connection to '${this.hostIdentifier}'`);
824
- return;
825
- // Remove the current keep-alive timer if it exists.
826
- this.clearKeepAliveTimer();
827
- // Write a notification to the logs.
828
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Connection to '${this.hostIdentifier}' timed out.`);
829
- // Close the connection to avoid re-use.
830
- // NOTE: This initiates reconnection routines if the connection has not
831
- // been marked as intentionally disconnected.
832
- this.socket.disconnect();
833
- }
834
- }
835
- /**
836
- * Updates the connection status when a connection is confirmed.
837
- */ onSocketConnect() {
838
- // If a reconnect timer is set, remove it.
839
- this.clearReconnectTimer();
840
- // Set up the initial timestamp for when we last received data from the server.
841
- this.lastReceivedTimestamp = Date.now();
842
- // Set up the initial keep-alive timer.
843
- this.setupKeepAliveTimer();
844
- // Clear all temporary error listeners.
845
- this.socket.removeAllListeners("error");
846
- // Set up handler for network errors.
847
- this.socket.on("error", this.onSocketError.bind(this));
848
- }
849
- /**
850
- * Updates the connection status when a connection is ended.
851
- */ onSocketDisconnect() {
852
- // Send a disconnect signal higher up the stack.
853
- this.emit("disconnect");
854
- // Remove the current keep-alive timer if it exists.
855
- this.clearKeepAliveTimer();
856
- // If this is a connection we're trying to tear down..
857
- if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTING) {
858
- // If a reconnect timer is set, remove it.
859
- this.clearReconnectTimer();
860
- // Remove all event listeners
861
- this.removeAllListeners();
862
- // Mark the connection as disconnected.
863
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;
864
- // Write a log message.
865
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Disconnected from '${this.hostIdentifier}'.`);
866
- } else {
867
- // If this is for an established connection..
868
- if (this.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) // Write a notification to the logs.
869
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(`Connection with '${this.hostIdentifier}' was closed, trying to reconnect in ${this.reconnectInterval / 1000} seconds.`);
870
- // Mark the connection as disconnected for now..
871
- this.status = (0, $db7c797e63383364$export$7516420eb880ab68).DISCONNECTED;
872
- // If we don't have a pending reconnection timer..
873
- if (!this.timers.reconnect) // Attempt to reconnect after one keep-alive duration.
874
- this.timers.reconnect = setTimeout(this.reconnect.bind(this), this.reconnectInterval);
875
- }
876
- }
877
- /**
878
- * Notify administrator of any unexpected errors.
879
- */ onSocketError(error) {
880
- // Report a generic error if no error information is present.
881
- // NOTE: When using WSS, the error event explicitly
882
- // only allows to send a "simple" event without data.
883
- // https://stackoverflow.com/a/18804298
884
- if (typeof error === "undefined") // Do nothing, and instead rely on the socket disconnect event for further information.
885
- return;
886
- // If the DNS lookup failed.
887
- if (error.code === "EAI_AGAIN") {
888
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(`Failed to look up DNS records for '${this.host}'.`);
889
- return;
890
- }
891
- // If the connection timed out..
892
- if (error.code === "ETIMEDOUT") {
893
- // Log the provided timeout message.
894
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(error.message);
895
- return;
896
- }
897
- // Log unknown error
898
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).errors(`Unknown network error ('${this.hostIdentifier}'): `, error);
899
- }
900
- }
901
- var // Export the connection.
902
- $ff134c9a9e1f7361$export$2e2bcd8739ae039 = $ff134c9a9e1f7361$var$ElectrumConnection;
903
-
904
-
905
-
906
-
907
-
908
-
909
- // Acceptable parameter types for RPC messages
910
- const $abcb763a48577a1e$export$d73a2e87a509880 = function(message) {
911
- return "id" in message && "error" in message;
912
- };
913
- const $abcb763a48577a1e$export$81276773828ff315 = function(message) {
914
- return "id" in message && "result" in message;
915
- };
916
- const $abcb763a48577a1e$export$280de919a0cf6928 = function(message) {
917
- return !("id" in message) && "method" in message;
918
- };
919
- const $abcb763a48577a1e$export$94e3360fcddccc76 = function(message) {
920
- return "id" in message && "method" in message;
921
- };
922
-
923
-
924
-
925
- /**
926
- * Triggers when the underlying connection is established.
927
- *
928
- * @event ElectrumClient#connected
929
- */ /**
930
- * Triggers when the underlying connection is lost.
931
- *
932
- * @event ElectrumClient#disconnected
933
- */ /**
934
- * Triggers when the remote server sends data that is not a request response.
935
- *
936
- * @event ElectrumClient#notification
937
- */ /**
938
- * High-level Electrum client that lets applications send requests and subscribe to notification events from a server.
939
- */ class $558b46d3f899ced5$var$ElectrumClient extends (0, $dvphU$EventEmitter) {
940
- /**
941
- * Initializes an Electrum client.
942
- *
943
- * @param {string} application your application name, used to identify to the electrum host.
944
- * @param {string} version protocol version to use with the host.
945
- * @param {string} host fully qualified domain name or IP number of the host.
946
- * @param {number} port the TCP network port of the host.
947
- * @param {TransportScheme} scheme the transport scheme to use for connection
948
- * @param {number} timeout how long network delays we will wait for before taking action, in milliseconds.
949
- * @param {number} pingInterval the time between sending pings to the electrum host, in milliseconds.
950
- * @param {number} reconnectInterval the time between reconnection attempts to the electrum host, in milliseconds.
951
- * @param {boolean} useBigInt whether to use bigint for numbers in json response.
952
- *
953
- * @throws {Error} if `version` is not a valid version string.
954
- */ constructor(application, version, host, port = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).PORT, scheme = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).TRANSPORT_SCHEME, timeout = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).TIMEOUT, pingInterval = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).PING_INTERVAL, reconnectInterval = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).RECONNECT, useBigInt = (0, $d801b1f9b7fc3074$export$f019be48b3aacb1a).USE_BIG_INT){
955
- // Initialize the event emitter.
956
- super();
957
- this.application = application;
958
- this.version = version;
959
- this.host = host;
960
- this.port = port;
961
- this.scheme = scheme;
962
- this.timeout = timeout;
963
- this.pingInterval = pingInterval;
964
- this.reconnectInterval = reconnectInterval;
965
- this.useBigInt = useBigInt;
966
- this.subscriptionMethods = {};
967
- this.requestId = 0;
968
- this.requestResolvers = {};
969
- this.connectionLock = new (0, $dvphU$Mutex)();
970
- // Set up a connection to an electrum server.
971
- this.connection = new (0, $ff134c9a9e1f7361$export$2e2bcd8739ae039)(application, version, host, port, scheme, timeout, pingInterval, reconnectInterval, useBigInt);
972
- }
973
- /**
974
- * Connects to the remote server.
975
- *
976
- * @throws {Error} if the socket connection fails.
977
- * @returns a promise resolving when the connection is established.
978
- */ async connect() {
979
- // Create a lock so that multiple connects/disconnects cannot race each other.
980
- const unlock = await this.connectionLock.acquire();
981
- try {
982
- // If we are already connected, do not attempt to connect again.
983
- if (this.connection.status === (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) return;
984
- // Listen for parsed statements.
985
- this.connection.on("statement", this.response.bind(this));
986
- // Hook up resubscription on connection.
987
- this.connection.on("connect", this.resubscribeOnConnect.bind(this));
988
- // Relay connect and disconnect events.
989
- this.connection.on("connect", this.emit.bind(this, "connected"));
990
- this.connection.on("disconnect", this.onConnectionDisconnect.bind(this));
991
- // Hook up client metadata gathering functions.
992
- this.connection.on("version", this.storeSoftwareVersion.bind(this));
993
- this.connection.on("received", this.updateLastReceivedTimestamp.bind(this));
994
- // Relay error events.
995
- this.connection.on("error", this.emit.bind(this, "error"));
996
- // Connect with the server.
997
- await this.connection.connect();
998
- } finally{
999
- unlock();
1000
- }
1001
- }
1002
- /**
1003
- * Disconnects from the remote server and removes all event listeners/subscriptions and open requests.
1004
- *
1005
- * @param {boolean} force disconnect even if the connection has not been fully established yet.
1006
- * @param {boolean} retainSubscriptions retain subscription data so they will be restored on reconnection.
1007
- *
1008
- * @returns true if successfully disconnected, or false if there was no connection.
1009
- */ async disconnect(force = false, retainSubscriptions = false) {
1010
- // Create a lock so that multiple connects/disconnects cannot race each other.
1011
- const unlock = await this.connectionLock.acquire();
1012
- try {
1013
- if (!retainSubscriptions) {
1014
- // Cancel all event listeners.
1015
- this.removeAllListeners();
1016
- // Remove all subscription data
1017
- this.subscriptionMethods = {};
1018
- }
1019
- // For each pending request..
1020
- for(const index in this.requestResolvers){
1021
- // Reject the request.
1022
- const requestResolver = this.requestResolvers[index];
1023
- requestResolver(new Error("Manual disconnection"));
1024
- // Remove the request.
1025
- delete this.requestResolvers[index];
1026
- }
1027
- // Disconnect from the remove server.
1028
- return await this.connection.disconnect(force);
1029
- } finally{
1030
- unlock();
1031
- }
1032
- }
1033
- /**
1034
- * Calls a method on the remote server with the supplied parameters.
1035
- *
1036
- * @param {string} method name of the method to call.
1037
- * @param {...string} parameters one or more parameters for the method.
1038
- *
1039
- * @throws {Error} if the client is disconnected.
1040
- * @returns a promise that resolves with the result of the method or an Error.
1041
- */ async request(method, ...parameters) {
1042
- // If we are not connected to a server..
1043
- if (this.connection.status !== (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) // Reject the request with a disconnected error message.
1044
- throw new Error(`Unable to send request to a disconnected server '${this.connection.host}'.`);
1045
- // Increase the request ID by one.
1046
- this.requestId += 1;
1047
- // Store a copy of the request id.
1048
- const id = this.requestId;
1049
- // Format the arguments as an electrum request object.
1050
- const message = (0, $24139611f53a54b8$export$2e2bcd8739ae039).buildRequestObject(method, parameters, id);
1051
- // Define a function to wrap the request in a promise.
1052
- const requestResolver = (resolve)=>{
1053
- // Add a request resolver for this promise to the list of requests.
1054
- this.requestResolvers[id] = (error, data)=>{
1055
- // If the resolution failed..
1056
- if (error) // Resolve the promise with the error for the application to handle.
1057
- resolve(error);
1058
- else // Resolve the promise with the request results.
1059
- resolve(data);
1060
- };
1061
- // Send the request message to the remote server.
1062
- this.connection.send(message);
1063
- };
1064
- // Write a log message.
1065
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).network(`Sending request '${method}' to '${this.connection.host}'`);
1066
- // return a promise to deliver results later.
1067
- return new Promise(requestResolver);
1068
- }
1069
- /**
1070
- * Subscribes to the method and payload at the server.
1071
- *
1072
- * @note the response for the subscription request is issued as a notification event.
1073
- *
1074
- * @param {string} method one of the subscribable methods the server supports.
1075
- * @param {...string} parameters one or more parameters for the method.
1076
- *
1077
- * @throws {Error} if the client is disconnected.
1078
- * @returns a promise resolving when the subscription is established.
1079
- */ async subscribe(method, ...parameters) {
1080
- // Initialize an empty list of subscription payloads, if needed.
1081
- if (!this.subscriptionMethods[method]) this.subscriptionMethods[method] = new Set();
1082
- // Store the subscription parameters to track what data we have subscribed to.
1083
- this.subscriptionMethods[method].add(JSON.stringify(parameters));
1084
- // Send initial subscription request.
1085
- const requestData = await this.request(method, ...parameters);
1086
- // Construct a notification structure to package the initial result as a notification.
1087
- const notification = {
1088
- jsonrpc: "2.0",
1089
- method: method,
1090
- params: [
1091
- ...parameters,
1092
- requestData
1093
- ]
1094
- };
1095
- // Manually emit an event for the initial response.
1096
- this.emit("notification", notification);
1097
- // Try to update the chain height.
1098
- this.updateChainHeightFromHeadersNotifications(notification);
1099
- }
1100
- /**
1101
- * Unsubscribes to the method at the server and removes any callback functions
1102
- * when there are no more subscriptions for the method.
1103
- *
1104
- * @param {string} method a previously subscribed to method.
1105
- * @param {...string} parameters one or more parameters for the method.
1106
- *
1107
- * @throws {Error} if no subscriptions exist for the combination of the provided `method` and `parameters.
1108
- * @throws {Error} if the client is disconnected.
1109
- * @returns a promise resolving when the subscription is removed.
1110
- */ async unsubscribe(method, ...parameters) {
1111
- // Throw an error if the client is disconnected.
1112
- if (this.connection.status !== (0, $db7c797e63383364$export$7516420eb880ab68).CONNECTED) throw new Error(`Unable to send unsubscribe request to a disconnected server '${this.connection.host}'.`);
1113
- // If this method has no subscriptions..
1114
- if (!this.subscriptionMethods[method]) // Reject this promise with an explanation.
1115
- throw new Error(`Cannot unsubscribe from '${method}' since the method has no subscriptions.`);
1116
- // Pack up the parameters as a long string.
1117
- const subscriptionParameters = JSON.stringify(parameters);
1118
- // If the method payload could not be located..
1119
- if (!this.subscriptionMethods[method].has(subscriptionParameters)) // Reject this promise with an explanation.
1120
- throw new Error(`Cannot unsubscribe from '${method}' since it has no subscription with the given parameters.`);
1121
- // Remove this specific subscription payload from internal tracking.
1122
- this.subscriptionMethods[method].delete(subscriptionParameters);
1123
- // Send unsubscription request to the server
1124
- // NOTE: As a convenience we allow users to define the method as the subscribe or unsubscribe version.
1125
- await this.request(method.replace(".subscribe", ".unsubscribe"), ...parameters);
1126
- // Write a log message.
1127
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).client(`Unsubscribed from '${String(method)}' for the '${subscriptionParameters}' parameters.`);
1128
- }
1129
- /**
1130
- * Restores existing subscriptions without updating status or triggering manual callbacks.
1131
- *
1132
- * @throws {Error} if subscription data cannot be found for all stored event names.
1133
- * @throws {Error} if the client is disconnected.
1134
- * @returns a promise resolving to true when the subscriptions are restored.
1135
- *
1136
- * @ignore
1137
- */ async resubscribeOnConnect() {
1138
- // Write a log message.
1139
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).client(`Connected to '${this.connection.hostIdentifier}'.`);
1140
- // Initialize an empty list of resubscription promises.
1141
- const resubscriptionPromises = [];
1142
- // For each method we have a subscription for..
1143
- for(const method in this.subscriptionMethods){
1144
- // .. and for each parameter we have previously been subscribed to..
1145
- for (const parameterJSON of this.subscriptionMethods[method].values()){
1146
- // restore the parameters from JSON.
1147
- const parameters = JSON.parse(parameterJSON);
1148
- // Send a subscription request.
1149
- resubscriptionPromises.push(this.subscribe(method, ...parameters));
1150
- }
1151
- // Wait for all re-subscriptions to complete.
1152
- await Promise.all(resubscriptionPromises);
1153
- }
1154
- // Write a log message if there was any subscriptions to restore.
1155
- if (resubscriptionPromises.length > 0) (0, $623a31cc1663a627$export$2e2bcd8739ae039).client(`Restored ${resubscriptionPromises.length} previous subscriptions for '${this.connection.hostIdentifier}'`);
1156
- }
1157
- /**
1158
- * Parser messages from the remote server to resolve request promises and emit subscription events.
1159
- *
1160
- * @param {RPCNotification | RPCResponse} message the response message
1161
- *
1162
- * @throws {Error} if the message ID does not match an existing request.
1163
- * @ignore
1164
- */ response(message) {
1165
- // If the received message is a notification, we forward it to all event listeners
1166
- if ((0, $abcb763a48577a1e$export$280de919a0cf6928)(message)) {
1167
- // Write a log message.
1168
- (0, $623a31cc1663a627$export$2e2bcd8739ae039).client(`Received notification for '${message.method}' from '${this.connection.host}'`);
1169
- // Forward the message content to all event listeners.
1170
- this.emit("notification", message);
1171
- // Try to update the chain height.
1172
- this.updateChainHeightFromHeadersNotifications(message);
1173
- // Return since it does not have an associated request resolver
1174
- return;
1175
- }
1176
- // If the response ID is null we cannot use it to index our request resolvers
1177
- if (message.id === null) // Throw an internal error, this should not happen.
1178
- throw new Error("Internal error: Received an RPC response with ID null.");
1179
- // Look up which request promise we should resolve this.
1180
- const requestResolver = this.requestResolvers[message.id];
1181
- // If we do not have a request resolver for this response message..
1182
- if (!requestResolver) // Throw an internal error, this should not happen.
1183
- throw new Error("Internal error: Callback for response not available.");
1184
- // Remove the promise from the request list.
1185
- delete this.requestResolvers[message.id];
1186
- // If the message contains an error..
1187
- if ((0, $abcb763a48577a1e$export$d73a2e87a509880)(message)) // Forward the message error to the request resolver and omit the `result` parameter.
1188
- requestResolver(new Error(message.error.message));
1189
- else {
1190
- // Forward the message content to the request resolver and omit the `error` parameter
1191
- // (by setting it to undefined).
1192
- requestResolver(undefined, message.result);
1193
- // Attempt to extract genesis hash from feature requests.
1194
- this.storeGenesisHashFromFeaturesResponse(message);
1195
- }
1196
- }
1197
- /**
1198
- * Callback function that is called when connection to the Electrum server is lost.
1199
- * Aborts all active requests with an error message indicating that connection was lost.
1200
- *
1201
- * @ignore
1202
- */ onConnectionDisconnect() {
1203
- // Emit a disconnection signal to any listeners.
1204
- this.emit("disconnected");
1205
- // Loop over active requests
1206
- for(const resolverId in this.requestResolvers){
1207
- // Extract request resolver for readability
1208
- const requestResolver = this.requestResolvers[resolverId];
1209
- // Resolve the active request with an error indicating that the connection was lost.
1210
- requestResolver(new Error("Connection lost"));
1211
- // Remove the promise from the request list.
1212
- delete this.requestResolvers[resolverId];
1213
- }
1214
- }
1215
- /**
1216
- * Stores the server provider software version field on successful version negotiation.
1217
- *
1218
- * @ignore
1219
- */ async storeSoftwareVersion(versionStatement) {
1220
- // TODO: handle failed version negotiation better.
1221
- if (versionStatement.error) // Do nothing.
1222
- return;
1223
- // Store the software version.
1224
- this.software = versionStatement.software;
1225
- }
1226
- /**
1227
- * Updates the last received timestamp.
1228
- *
1229
- * @ignore
1230
- */ async updateLastReceivedTimestamp() {
1231
- // Update the timestamp for when we last received data.
1232
- this.lastReceivedTimestamp = Date.now();
1233
- }
1234
- /**
1235
- * Checks if the provided message is a response to a headers subscription,
1236
- * and if so updates the locally stored chain height value for this client.
1237
- *
1238
- * @ignore
1239
- */ async updateChainHeightFromHeadersNotifications(message) {
1240
- // If the message is a notification for a new chain height..
1241
- if (message.method === "blockchain.headers.subscribe") // ..also store the updated chain height locally.
1242
- this.chainHeight = message.params[0].height;
1243
- }
1244
- /**
1245
- * Checks if the provided message is a response to a server.features request,
1246
- * and if so stores the genesis hash for this client locally.
1247
- *
1248
- * @ignore
1249
- */ async storeGenesisHashFromFeaturesResponse(message) {
1250
- // If the message is a response to a features request..
1251
- if (message.result.genesis_hash) // ..store the genesis hash locally.
1252
- this.genesisHash = message.result.genesis_hash;
1253
- }
1254
- }
1255
- var // Export the client.
1256
- $558b46d3f899ced5$export$2e2bcd8739ae039 = $558b46d3f899ced5$var$ElectrumClient;
1257
-
1258
-
1259
-
1260
-
1261
-
1262
-
1263
-
1264
- export {$558b46d3f899ced5$export$2e2bcd8739ae039 as ElectrumClient, $e83d2e7688025acd$export$e1f38ab2b4ebdde6 as isVersionRejected, $e83d2e7688025acd$export$9598f0c76aa41d73 as isVersionNegotiated, $d801b1f9b7fc3074$export$d048df559e6d3842 as ElectrumTransport, $d801b1f9b7fc3074$export$f019be48b3aacb1a as DefaultParameters, $db7c797e63383364$export$c4f81c6d30ca200f as ClientState, $db7c797e63383364$export$7516420eb880ab68 as ConnectionStatus};
1265
- //# sourceMappingURL=index.mjs.map