UNPKG

@electrum-cash/network

Version:

@electrum-cash/network is a lightweight JavaScript library that lets you connect with one or more Electrum servers.

450 lines (448 loc) 14.5 kB
import { EventEmitter } from "eventemitter3"; //#region source/enums.d.ts /** * Enum that denotes the connection status of an ElectrumConnection. * @enum {number} * @property {0} DISCONNECTED The connection is disconnected. * @property {1} AVAILABLE The connection is connected. * @property {2} DISCONNECTING The connection is disconnecting. * @property {3} CONNECTING The connection is connecting. * @property {4} RECONNECTING The connection is restarting. */ declare enum ConnectionStatus { DISCONNECTED = 0, CONNECTED = 1, DISCONNECTING = 2, CONNECTING = 3, RECONNECTING = 4, } //#endregion //#region source/rpc-interfaces.d.ts type RPCParameter = string | number | boolean | object | null; type RCPIdentifier = number | string | null; interface RPCBase { jsonrpc: string; } interface RPCNotification extends RPCBase { method: string; params?: RPCParameter[]; } interface RPCRequest extends RPCBase { id: RCPIdentifier; method: string; params?: RPCParameter[]; } interface RPCStatement extends RPCBase { id: RCPIdentifier; result: string; } interface RPCError { code: number; message: string; data?: unknown; } interface RPCErrorResponse extends RPCBase { id: RCPIdentifier; error: RPCError; } type RPCResponse = RPCErrorResponse | RPCStatement | RPCNotification; type RPCMessage = RPCNotification | RPCRequest | RPCResponse; type RPCResponseBatch = RPCResponse[]; type RPCRequestBatch = RPCRequest[]; declare const isRPCErrorResponse: (message: RPCBase) => message is RPCErrorResponse; declare const isRPCStatement: (message: RPCBase) => message is RPCStatement; declare const isRPCNotification: (message: RPCBase) => message is RPCNotification; declare const isRPCRequest: (message: RPCBase) => message is RPCRequest; //#endregion //#region source/interfaces.d.ts /** * Optional settings that change the default behavior of the network connection. */ interface ElectrumNetworkOptions { /** If set to true, numbers that can safely be parsed as integers will be `BigInt` rather than `Number`. */ useBigInt?: boolean; /** When connected, send a keep-alive Ping message this often. */ sendKeepAliveIntervalInMilliSeconds?: number; /** When disconnected, attempt to reconnect after this amount of time. */ reconnectAfterMilliSeconds?: number; /** After every send, verify that we have received data after this amount of time. */ verifyConnectionTimeoutInMilliSeconds?: number; /** Turn off automatic handling of browser visibility, which disconnects when application is not visible to be consistent across browsers. */ disableBrowserVisibilityHandling?: boolean; /** Turn off automatic handling of browser connectivity. */ disableBrowserConnectivityHandling?: boolean; } /** * List of events emitted by the ElectrumSocket. * @event * @ignore */ interface ElectrumSocketEvents { /** * Emitted when data has been received over the socket. * @eventProperty */ 'data': [string]; /** * Emitted when a socket connects. * @eventProperty */ 'connected': []; /** * Emitted when a socket disconnects. * @eventProperty */ 'disconnected': []; /** * Emitted when the socket has failed in some way. * @eventProperty */ 'error': [Error]; } /** * Abstract socket used when communicating with Electrum servers. */ interface ElectrumSocket extends EventEmitter<ElectrumSocketEvents>, ElectrumSocketEvents { /** * Utility function to provide a human accessible host identifier. */ get hostIdentifier(): string; /** * Fully qualified domain name or IP address of the host */ host: string; /** * Network port for the host to connect to, defaults to the standard TLS port */ port: number; /** * If false, uses an unencrypted connection instead of the default on TLS */ encrypted: boolean; /** * If no connection is established after `timeout` ms, the connection is terminated */ timeout: number; /** * Connects to an Electrum server using the socket. */ connect(): void; /** * Disconnects from the Electrum server from the socket. */ disconnect(): void; /** * Write data to the Electrum server on the socket. * * @param data - Data to be written to the socket * @param callback - Callback function to be called when the write has completed */ write(data: Uint8Array | string, callback?: (err?: Error) => void): boolean; } /** * @ignore */ interface VersionRejected { error: RPCError; } /** * @ignore */ interface VersionNegotiated { software: string; protocol: string; } /** * @ignore */ type VersionNegotiationResponse = VersionNegotiated | VersionRejected; /** * List of events emitted by the ElectrumConnection. * @event * @ignore */ interface ElectrumConnectionEvents { /** * Emitted when any data has been received over the network. * @eventProperty */ 'received': []; /** * Emitted when a complete electrum message has been received over the network. * @eventProperty */ 'response': [RPCResponse]; /** * Emitted when the connection has completed version negotiation. * @eventProperty */ 'version': [VersionNegotiationResponse]; /** * Emitted when a network connection is initiated. * @eventProperty */ 'connecting': []; /** * Emitted when a network connection is successful. * @eventProperty */ 'connected': []; /** * Emitted when a network disconnection is initiated. * @eventProperty */ 'disconnecting': []; /** * Emitted when a network disconnection is successful. * @eventProperty */ 'disconnected': []; /** * Emitted when a network connect attempts to automatically reconnect. * @eventProperty */ 'reconnecting': []; /** * Emitted when the network has failed in some way. * @eventProperty */ 'error': [Error]; } /** * List of events emitted by the ElectrumClient. * @event * @ignore */ interface ElectrumClientEvents { /** * Emitted when an electrum subscription statement has been received over the network. * @eventProperty */ 'notification': [RPCNotification]; /** * Emitted when a network connection is initiated. * @eventProperty */ 'connecting': []; /** * Emitted when a network connection is successful. * @eventProperty */ 'connected': []; /** * Emitted when a network disconnection is initiated. * @eventProperty */ 'disconnecting': []; /** * Emitted when a network disconnection is successful. * @eventProperty */ 'disconnected': []; /** * Emitted when a network connect attempts to automatically reconnect. * @eventProperty */ 'reconnecting': []; /** * Emitted when the network has failed in some way. * @eventProperty */ 'error': [Error]; } /** * A list of possible responses to requests. * @ignore */ type RequestResponse = RPCParameter | RPCParameter[]; /** * Request resolvers are used to process the response of a request. This takes either * an error object or any stringified data, while the other parameter is omitted. * @ignore */ type RequestResolver = (error?: Error, data?: string) => void; /** * Typing for promise resolution. * @ignore */ type ResolveFunction<T> = (value: T | PromiseLike<T>) => void; /** * Typing for promise rejection. * @ignore */ type RejectFunction = (reason?: unknown) => void; /** * @ignore */ declare const isVersionRejected: (object: VersionNegotiationResponse) => object is VersionRejected; /** * @ignore */ declare const isVersionNegotiated: (object: VersionNegotiationResponse) => object is VersionNegotiated; //#endregion //#region source/electrum-client.d.ts /** * High-level Electrum client that lets applications send requests and subscribe to notification events from a server. */ declare class ElectrumClient<ElectrumEvents extends ElectrumClientEvents> extends EventEmitter<ElectrumClientEvents | ElectrumEvents> implements ElectrumClientEvents { application: string; version: string; socketOrHostname: ElectrumSocket | string; options: ElectrumNetworkOptions; /** * The name and version of the server software indexing the blockchain. */ software: string; /** * The genesis hash of the blockchain indexed by the server. * @remarks This is only available after a 'server.features' call. */ genesisHash: string; /** * The chain height of the blockchain indexed by the server. * @remarks This is only available after a 'blockchain.headers.subscribe' call. */ chainHeight: number; /** * Timestamp of when we last received data from the server indexing the blockchain. */ lastReceivedTimestamp: number; /** * Number corresponding to the underlying connection status. */ get status(): ConnectionStatus; private connection; private subscriptionMethods; private requestId; private requestResolvers; private connectionLock; /** * Initializes an Electrum client. * * @param application - your application name, used to identify to the electrum host. * @param version - protocol version to use with the host. * @param socketOrHostname - pre-configured electrum socket or fully qualified domain name or IP number of the host * @param options - ... * * @throws {Error} if `version` is not a valid version string. */ constructor(application: string, version: string, socketOrHostname: ElectrumSocket | string, options?: ElectrumNetworkOptions); get hostIdentifier(): string; get encrypted(): boolean; /** * Connects to the remote server. * * @throws {Error} if the socket connection fails. * @returns a promise resolving when the connection is established. */ connect(): Promise<void>; /** * Disconnects from the remote server and removes all event listeners/subscriptions and open requests. * * @param force - disconnect even if the connection has not been fully established yet. * @param retainSubscriptions - retain subscription data so they will be restored on reconnection. * * @returns true if successfully disconnected, or false if there was no connection. */ disconnect(force?: boolean, retainSubscriptions?: boolean): Promise<boolean>; /** * Calls a method on the remote server with the supplied parameters. * * @param method - name of the method to call. * @param parameters - one or more parameters for the method. * * @throws {Error} if the client is disconnected. * @returns a promise that resolves with the result of the method or an Error. */ request(method: string, ...parameters: RPCParameter[]): Promise<Error | RequestResponse>; /** * Subscribes to the method and payload at the server. * * @remarks the response for the subscription request is issued as a notification event. * * @param method - one of the subscribable methods the server supports. * @param parameters - one or more parameters for the method. * * @throws {Error} if the client is disconnected. * @returns a promise resolving when the subscription is established. */ subscribe(method: string, ...parameters: RPCParameter[]): Promise<void>; /** * Unsubscribes to the method at the server and removes any callback functions * when there are no more subscriptions for the method. * * @param method - a previously subscribed to method. * @param parameters - one or more parameters for the method. * * @throws {Error} if no subscriptions exist for the combination of the provided `method` and `parameters. * @throws {Error} if the client is disconnected. * @returns a promise resolving when the subscription is removed. */ unsubscribe(method: string, ...parameters: RPCParameter[]): Promise<void>; /** * Restores existing subscriptions without updating status or triggering manual callbacks. * * @throws {Error} if subscription data cannot be found for all stored event names. * @throws {Error} if the client is disconnected. * @returns a promise resolving to true when the subscriptions are restored. * * @ignore */ private resubscribeOnConnect; /** * Parser messages from the remote server to resolve request promises and emit subscription events. * * @param message - the response message * * @throws {Error} if the message ID does not match an existing request. * @ignore */ response(message: RPCResponse): void; /** * Callback function that is called when connection to the Electrum server is lost. * Aborts all active requests with an error message indicating that connection was lost. * * @ignore */ onConnectionDisconnect(): Promise<void>; /** * Stores the server provider software version field on successful version negotiation. * * @ignore */ storeSoftwareVersion(versionStatement: any): Promise<void>; /** * Updates the last received timestamp. * * @ignore */ updateLastReceivedTimestamp(): Promise<void>; /** * Checks if the provided message is a response to a headers subscription, * and if so updates the locally stored chain height value for this client. * * @ignore */ updateChainHeightFromHeadersNotifications(message: any): Promise<void>; /** * Checks if the provided message is a response to a server.features request, * and if so stores the genesis hash for this client locally. * * @ignore */ storeGenesisHashFromFeaturesResponse(message: any): Promise<void>; /** * Helper function to synchronize state and events with the underlying connection. */ handleConnectionStatusChanges(eventName: any): Promise<void>; readonly connecting: []; readonly connected: []; readonly disconnecting: []; readonly disconnected: []; readonly reconnecting: []; readonly notification: [RPCNotification]; readonly error: [Error]; } //#endregion export { ConnectionStatus, ElectrumClient, ElectrumClientEvents, ElectrumConnectionEvents, ElectrumNetworkOptions, ElectrumSocket, ElectrumSocketEvents, RCPIdentifier, RPCBase, RPCError, RPCErrorResponse, RPCMessage, RPCNotification, RPCParameter, RPCRequest, RPCRequestBatch, RPCResponse, RPCResponseBatch, RPCStatement, RejectFunction, RequestResolver, RequestResponse, ResolveFunction, VersionNegotiated, VersionNegotiationResponse, VersionRejected, isRPCErrorResponse, isRPCNotification, isRPCRequest, isRPCStatement, isVersionNegotiated, isVersionRejected }; //# sourceMappingURL=index.d.mts.map