Merge branch 'release/1.2.0'

This commit is contained in:
Pavel Ševčík
2022-03-01 21:59:42 +01:00
23 changed files with 7042 additions and 710 deletions

12
.editorconfig Normal file
View File

@@ -0,0 +1,12 @@
root = true
[*]
charset = utf-8
end_of_line = lf
[{*.js, *.ts}]
trim_trailing_whitespace = true
insert_final_newline = true
max_line_length = 160
indent_size = 4
indent_style = space

106
.eslintrc.json Normal file
View File

@@ -0,0 +1,106 @@
{
"env": {
"node": true,
"es2021": true,
"mocha": true
},
"parser": "@typescript-eslint/parser",
"plugins": [
"@typescript-eslint",
"import",
"unicorn"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:import/recommended",
"plugin:unicorn/recommended"
],
"ignorePatterns": ["*.min.js"],
"parserOptions": {
"ecmaVersion": 13,
"sourceType": "module"
},
"rules": {
"array-callback-return": [
"error",
{
"checkForEach": true
}
],
"complexity": "error",
"no-constructor-return": "error",
"no-self-compare": "error",
"no-template-curly-in-string": "warn",
"no-unmodified-loop-condition": "warn",
"no-unreachable-loop": "error",
"require-atomic-updates": "error",
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"never"
],
"max-len": [
"warn",
160
],
"eol-last": "error",
"eqeqeq": [
"error",
"smart"
],
"radix": "error",
"dot-notation": "warn",
"no-array-constructor": "error",
"no-extend-native": "error",
"no-extra-bind": "error",
"no-implicit-coercion": "error",
"no-invalid-this": "error",
"no-iterator": "error",
"no-lonely-if": "error",
"no-loop-func": "error",
"no-multi-assign": "error",
"no-negated-condition": "error",
"no-undef-init": "error",
"no-useless-call": "error",
"no-useless-constructor": "error",
"no-useless-return": "error",
"prefer-arrow-callback": "warn",
"prefer-template": "warn",
"import/no-self-import": "error",
"import/no-cycle": "error",
"import/no-useless-path-segments": "error",
"import/no-deprecated": "warn",
"import/no-extraneous-dependencies": "error",
"import/no-mutable-exports": "error",
"import/first": "error",
"import/no-duplicates": "error",
"import/newline-after-import": "error",
"import/extensions": [
"off",
"ignorePackages"
],
"import/no-unresolved": "off",
"unicorn/no-null": "off",
"unicorn/no-process-exit": "off",
"unicorn/prefer-node-protocol": "off",
"unicorn/prevent-abbreviations": "off",
"unicorn/no-array-for-each": "warn",
"unicorn/numeric-separators-style": "off",
"unicorn/require-post-message-target-origin": "off",
"unicorn/no-array-reduce": "off"
}
}

7
.gitignore vendored
View File

@@ -57,3 +57,10 @@ typings/
# dotenv environment variables file
.env
# dist folder
dist/
# vscode files
.vscode

6
.mocharc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"extension": ["ts"],
"node-option": ["experimental-specifier-resolution=node", "loader=ts-node/esm"],
"spec": ["test/**/*.test.ts"],
"timeout": 20000
}

10
.npmignore Normal file
View File

@@ -0,0 +1,10 @@
src/
test/
.vscode/
.idea/
.gitignore
.mocharc.json
.editorconfig
.eslintrc.json
tsconfig*

7
CHANGELOG.md Normal file
View File

@@ -0,0 +1,7 @@
# Changelog
## 1.2.0 (2022-03-01)
- Complete rewrite to Typescript
- Added mocha tests
- Added ESlint
- Minor changes and fixes

76
LICENSE
View File

@@ -1,21 +1,63 @@
MIT License
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (c) 2017 Yuki Akiyama
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
0. Additional Definitions.
As used herein, “this License” refers to version 3 of the GNU Lesser General Public License, and the “GNU GPL” refers to version 3 of the GNU General Public License.
“The Library” refers to a covered work governed by this License, other than an Application or a Combined Work as defined below.
An “Application” is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library.
A “Combined Work” is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the “Linked Version”.
The “Minimal Corresponding Source” for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version.
The “Corresponding Application Code” for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version:
a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following:
a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license document.
c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.
1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.
e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the Library side by side in a single library together with other library facilities that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions of the GNU Lesser General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library as you received it specifies that a certain numbered version of the GNU Lesser General Public License “or any later version” applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library.

View File

@@ -1,23 +1,45 @@
# electrum-client
# @samouraiwallet/electrum-client
Electrum Protocol Client for node.js.
Electrum Protocol client for Node.js.
# based on
This library uses ESModules, Node.js v14 or higher is required.
# Based on
* https://github.com/mempool/electrum-client
* https://github.com/you21979/node-electrum-client
* https://github.com/7kharov/node-electrum-client
* https://github.com/BlueWallet/rn-electrum-client
# features
# Features
* persistence (ping strategy and reconnection)
* batch requests
* works in RN and nodejs
* Persistence (ping strategy and reconnection)
* Batch requests
* Promise API
* Fully typed (Typescript)
## protocol spec
## Protocol spec
* https://electrumx.readthedocs.io/en/latest/PROTOCOL.html
## usage
## Usage
Relies on `net` so will only run in NodeJS environment.
```js
import {ElectrumClient} from "@samouraiwallet/electrum-client";
const run = async () => {
tcpClient = new ElectrumClient(60001, 'btc.electroncash.dk', 'tcp');
await tcpClient.initElectrum({client: 'electrum-client-js', version: ['1.2', '1.4']}, {
retryPeriod: 5000,
maxRetry: 10,
pingPeriod: 5000,
});
const rawTx = await tcpClient.blockchainTransaction_get('b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a');
return rawTx;
// result: 02000000016016c6d039cbdeefa655e4b5ac61ec2b5fe16920529f086a2439f59a5994bed6200000006a4730440220421b5daf5f72e514075d256121d6b66e1d9a8993d37ceb0532baca11f6964da502205333d1c4b9be749180bfa8da4da6a07c0e9e2d853c809a75c4b60ef717a628b20121029139c783aa8f31707a67248a6a6b643855e9d1484dbd53cfe7d9e3adf3ce7098ffffffff02c19a01000000000017a9146eda8b447af853746f04b902fea5b2cd959d866d87692c0200000000001976a914443674ce759f8fa2fe83a6608339da782b890c1988ac00000000
}
```

266
index.js
View File

@@ -1,266 +0,0 @@
'use strict';
const Client = require('./lib/client');
class ElectrumClient extends Client {
constructor(port, host, protocol, options, callbacks) {
super(port, host, protocol, options, callbacks);
this.onConnectCallback = (callbacks && callbacks.onConnect) ? callbacks.onConnect : null;
this.onCloseCallback = (callbacks && callbacks.onClose) ? callbacks.onClose : null;
this.onLogCallback = (callbacks && callbacks.onLog) ? callbacks.onLog : function(str) {
console.log(str);
};
this.timeLastCall = 0;
}
initElectrum(electrumConfig, persistencePolicy = { retryPeriod: 10000, maxRetry: 1000, pingPeriod: 120000, callback: null }) {
this.persistencePolicy = persistencePolicy;
this.electrumConfig = electrumConfig;
this.timeLastCall = 0;
return new Promise((resolve, reject) => {
this.connect().then(() => {
this.server_version(this.electrumConfig.client, this.electrumConfig.version).then((versionInfo) => {
this.versionInfo = versionInfo;
if (this.onConnectCallback != null) {
this.onConnectCallback(this, this.versionInfo);
}
resolve(this);
}).catch((err) => {
reject(err);
});
}).catch((err) => {
reject(err);
});
});
}
// Override parent
request(method, params) {
this.timeLastCall = new Date().getTime();
const parentPromise = super.request(method, params);
return parentPromise.then(response => {
this.keepAlive();
return response;
});
}
requestBatch(method, params, secondParam) {
this.timeLastCall = new Date().getTime();
const parentPromise = super.requestBatch(method, params, secondParam);
return parentPromise.then(response => {
this.keepAlive();
return response;
});
}
onClose() {
super.onClose();
const list = [
'server.peers.subscribe',
'blockchain.numblocks.subscribe',
'blockchain.headers.subscribe',
'blockchain.address.subscribe',
];
list.forEach(event => this.subscribe.removeAllListeners(event));
var retryPeriod = 10000;
if (this.persistencePolicy != null && this.persistencePolicy.retryPeriod > 0) {
retryPeriod = this.persistencePolicy.retryPeriod;
}
if (this.onCloseCallback != null) {
this.onCloseCallback(this);
}
setTimeout(() => {
if (this.persistencePolicy != null && this.persistencePolicy.maxRetry > 0) {
this.reconnect().catch((err) => {
this.onError(err);
});
this.persistencePolicy.maxRetry -= 1;
} else if (this.persistencePolicy != null && this.persistencePolicy.callback != null) {
this.persistencePolicy.callback();
} else if (this.persistencePolicy == null) {
this.reconnect().catch((err) => {
this.onError(err);
});
}
}, retryPeriod);
}
// ElectrumX persistancy
keepAlive() {
if (this.timeout != null) {
clearTimeout(this.timeout);
}
var pingPeriod = 120000;
if (this.persistencePolicy != null && this.persistencePolicy.pingPeriod > 0) {
pingPeriod = this.persistencePolicy.pingPeriod;
}
this.timeout = setTimeout(() => {
if (this.timeLastCall !== 0 && new Date().getTime() > this.timeLastCall + pingPeriod) {
this.server_ping().catch((reason) => {
this.log('Keep-Alive ping failed: ', reason);
});
}
}, pingPeriod);
}
close() {
super.close();
if (this.timeout != null) {
clearTimeout(this.timeout);
}
this.reconnect = this.reconnect = this.onClose = this.keepAlive = () => {}; // dirty hack to make it stop reconnecting
}
reconnect() {
this.log("Electrum attempting reconnect...");
this.initSocket();
if (this.persistencePolicy != null) {
return this.initElectrum(this.electrumConfig, this.persistencePolicy);
} else {
return this.initElectrum(this.electrumConfig);
}
}
log(str) {
this.onLogCallback(str);
}
// ElectrumX API
server_version(client_name, protocol_version) {
return this.request('server.version', [client_name, protocol_version]);
}
server_banner() {
return this.request('server.banner', []);
}
server_features() {
return this.request('server.features', []);
}
server_ping() {
return this.request('server.ping', []);
}
server_addPeer(features) {
return this.request('server.add_peer', [features]);
}
serverDonation_address() {
return this.request('server.donation_address', []);
}
serverPeers_subscribe() {
return this.request('server.peers.subscribe', []);
}
blockchainAddress_getProof(address) {
return this.request('blockchain.address.get_proof', [address]);
}
blockchainScripthash_getBalance(scripthash) {
return this.request('blockchain.scripthash.get_balance', [scripthash]);
}
blockchainScripthash_getBalanceBatch(scripthash) {
return this.requestBatch('blockchain.scripthash.get_balance', scripthash);
}
blockchainScripthash_listunspentBatch(scripthash) {
return this.requestBatch('blockchain.scripthash.listunspent', scripthash);
}
blockchainScripthash_getHistory(scripthash) {
return this.request('blockchain.scripthash.get_history', [scripthash]);
}
blockchainScripthash_getHistoryBatch(scripthash) {
return this.requestBatch('blockchain.scripthash.get_history', scripthash);
}
blockchainScripthash_getMempool(scripthash) {
return this.request('blockchain.scripthash.get_mempool', [scripthash]);
}
blockchainScripthash_listunspent(scripthash) {
return this.request('blockchain.scripthash.listunspent', [scripthash]);
}
blockchainScripthash_subscribe(scripthash) {
return this.request('blockchain.scripthash.subscribe', [scripthash]);
}
blockchainBlock_getHeader(height) {
return this.request('blockchain.block.get_header', [height]);
}
blockchainBlock_headers(start_height, count) {
return this.request('blockchain.block.headeres', [start_height, count]);
}
blockchainEstimatefee(number) {
return this.request('blockchain.estimatefee', [number]);
}
blockchainHeaders_subscribe(raw) {
return this.request('blockchain.headers.subscribe', [raw || false]);
}
blockchain_relayfee() {
return this.request('blockchain.relayfee', []);
}
blockchainTransaction_broadcast(rawtx) {
return this.request('blockchain.transaction.broadcast', [rawtx]);
}
blockchainTransaction_get(tx_hash, verbose) {
return this.request('blockchain.transaction.get', [tx_hash, verbose || false]);
}
blockchainTransaction_getBatch(tx_hash, verbose) {
return this.requestBatch('blockchain.transaction.get', tx_hash, verbose);
}
blockchainTransaction_getMerkle(tx_hash, height) {
return this.request('blockchain.transaction.get_merkle', [tx_hash, height]);
}
mempool_getFeeHistogram() {
return this.request('mempool.get_fee_histogram', []);
}
// ---------------------------------
// protocol 1.1 deprecated method
// ---------------------------------
blockchainUtxo_getAddress(tx_hash, index) {
return this.request('blockchain.utxo.get_address', [tx_hash, index]);
}
blockchainNumblocks_subscribe() {
return this.request('blockchain.numblocks.subscribe', []);
}
// ---------------------------------
// protocol 1.2 deprecated method
// ---------------------------------
blockchainBlock_getChunk(index) {
return this.request('blockchain.block.get_chunk', [index]);
}
blockchainAddress_getBalance(address) {
return this.request('blockchain.address.get_balance', [address]);
}
blockchainAddress_getHistory(address) {
return this.request('blockchain.address.get_history', [address]);
}
blockchainAddress_getMempool(address) {
return this.request('blockchain.address.get_mempool', [address]);
}
blockchainAddress_listunspent(address) {
return this.request('blockchain.address.listunspent', [address]);
}
blockchainAddress_subscribe(address) {
return this.request('blockchain.address.subscribe', [address]);
}
}
module.exports = ElectrumClient;

View File

@@ -1,125 +0,0 @@
/**
* Simple wrapper to mimick Socket class from NET package, since TLS package has slightly different API.
* We implement several methods that TCP sockets are expected to have. We will proxy call them as soon as
* real TLS socket will be created (TLS socket created after connection).
*/
class TlsSocketWrapper {
constructor(tls) {
this._tls = tls; // dependency injection lol
this._socket = false;
// defaults:
this._timeout = 5000;
this._encoding = 'utf8';
this._keepAliveEneblad = true;
this._keepAliveinitialDelay = 0;
this._noDelay = true;
this._listeners = {};
}
setTimeout(timeout) {
if (this._socket) this._socket.setTimeout(timeout);
this._timeout = timeout;
}
setEncoding(encoding) {
if (this._socket) this._socket.setEncoding(encoding);
this._encoding = encoding;
}
setKeepAlive(enabled, initialDelay) {
if (this._socket) this._socket.setKeepAlive(enabled, initialDelay);
this._keepAliveEneblad = enabled;
this._keepAliveinitialDelay = initialDelay;
}
setNoDelay(noDelay) {
if (this._socket) this._socket.setNoDelay(noDelay);
this._noDelay = noDelay;
}
on(event, listener) {
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
}
removeListener(event, listener) {
this._listeners[event] = this._listeners[event] || [];
let newListeners = [];
let found = false;
for (let savedListener of this._listeners[event]) {
if (savedListener == listener) {
// found our listener
found = true;
// we just skip it
} else {
// other listeners should go back to original array
newListeners.push(savedListener);
}
}
if (found) {
this._listeners[event] = newListeners;
} else {
// something went wrong, lets just cleanup all listeners
this._listeners[event] = [];
}
}
connect(port, host, callback) {
// resulting TLSSocket extends <net.Socket>
this._socket = this._tls.connect({ port: port, host: host, rejectUnauthorized: false }, () => {
return callback();
});
// setting everything that was set to this proxy class
this._socket.setTimeout(this._timeout);
this._socket.setEncoding(this._encoding);
this._socket.setKeepAlive(this._keepAliveEneblad, this._keepAliveinitialDelay);
this._socket.setNoDelay(this._noDelay);
// resubscribing to events on newly created socket so we could proxy them to already established listeners
this._socket.on('data', data => {
this._passOnEvent('data', data);
});
this._socket.on('error', data => {
this._passOnEvent('error', data);
});
this._socket.on('close', data => {
this._passOnEvent('close', data);
});
this._socket.on('connect', data => {
this._passOnEvent('connect', data);
});
this._socket.on('connection', data => {
this._passOnEvent('connection', data);
});
}
_passOnEvent(event, data) {
this._listeners[event] = this._listeners[event] || [];
for (let savedListener of this._listeners[event]) {
savedListener(data);
}
}
emit(event, data) {
this._socket.emit(event, data);
}
end() {
this._socket.end();
}
destroy() {
this._socket.destroy();
}
write(data) {
this._socket.write(data);
}
}
module.exports = TlsSocketWrapper;

View File

@@ -1,198 +0,0 @@
'use strict';
let net = require('net');
let tls = require('tls');
const TIMEOUT = 5000;
const TlsSocketWrapper = require('./TlsSocketWrapper.js');
const EventEmitter = require('events').EventEmitter;
const util = require('./util');
class Client {
constructor(port, host, protocol, options, callbacks) {
this.id = 0;
this.port = port;
this.host = host;
this.callback_message_queue = {};
this.subscribe = new EventEmitter();
this.mp = new util.MessageParser((body, n) => {
this.onMessage(body, n);
});
this._protocol = protocol; // saving defaults
this._options = options;
this.onErrorCallback = (callbacks && callbacks.onError) ? callbacks.onError : null;
this.initSocket(protocol, options);
}
initSocket(protocol, options) {
protocol = protocol || this._protocol;
options = options || this._options;
switch (protocol) {
case 'tcp':
this.conn = new net.Socket();
break;
case 'tls':
case 'ssl':
if (!tls) {
throw new Error("Package 'tls' not available");
}
this.conn = new TlsSocketWrapper(tls);
break;
default:
throw new Error('unknown protocol');
}
this.conn.setTimeout(TIMEOUT);
this.conn.setEncoding('utf8');
this.conn.setKeepAlive(true, 0);
this.conn.setNoDelay(true);
this.conn.on('connect', () => {
this.conn.setTimeout(0);
this.onConnect();
});
this.conn.on('close', e => {
this.onClose(e);
});
this.conn.on('data', chunk => {
this.conn.setTimeout(0);
this.onRecv(chunk);
});
this.conn.on('error', e => {
this.onError(e);
});
this.status = 0;
}
connect() {
if (this.status === 1) {
return Promise.resolve();
}
this.status = 1;
return this.connectSocket(this.conn, this.port, this.host);
}
connectSocket(conn, port, host) {
return new Promise((resolve, reject) => {
const errorHandler = e => reject(e);
conn.on('error', errorHandler);
conn.connect(port, host, () => {
conn.removeListener('error', errorHandler);
resolve();
});
});
}
close() {
if (this.status === 0) {
return;
}
this.conn.end();
this.conn.destroy();
this.status = 0;
}
request(method, params) {
if (this.status === 0) {
return Promise.reject(new Error('Connection to server lost, please retry'));
}
return new Promise((resolve, reject) => {
const id = ++this.id;
const content = util.makeRequest(method, params, id);
this.callback_message_queue[id] = util.createPromiseResult(resolve, reject);
this.conn.write(content + '\n');
});
}
requestBatch(method, params, secondParam) {
if (this.status === 0) {
return Promise.reject(new Error('Connection to server lost, please retry'));
}
return new Promise((resolve, reject) => {
let arguments_far_calls = {};
let contents = [];
for (let param of params) {
const id = ++this.id;
if (secondParam !== undefined) {
contents.push(util.makeRequest(method, [param, secondParam], id));
} else {
contents.push(util.makeRequest(method, [param], id));
}
arguments_far_calls[id] = param;
}
const content = '[' + contents.join(',') + ']';
this.callback_message_queue[this.id] = util.createPromiseResultBatch(resolve, reject, arguments_far_calls);
// callback will exist only for max id
this.conn.write(content + '\n');
});
}
response(msg) {
let callback;
if (!msg.id && msg[0] && msg[0].id) {
// this is a response from batch request
for (let m of msg) {
if (m.id && this.callback_message_queue[m.id]) {
callback = this.callback_message_queue[m.id];
delete this.callback_message_queue[m.id];
}
}
} else {
callback = this.callback_message_queue[msg.id];
}
if (callback) {
delete this.callback_message_queue[msg.id];
if (msg.error) {
callback(msg.error);
} else {
callback(null, msg.result || msg);
}
} else {
throw new Error("Error getting callback while handling response");
}
}
onMessage(body, n) {
const msg = JSON.parse(body);
if (msg instanceof Array) {
this.response(msg);
} else {
if (msg.id !== void 0) {
this.response(msg);
} else {
this.subscribe.emit(msg.method, msg.params);
}
}
}
onConnect() {
}
onClose(e) {
this.status = 0;
Object.keys(this.callback_message_queue).forEach(key => {
this.callback_message_queue[key](new Error('close connect'));
delete this.callback_message_queue[key];
});
}
onRecv(chunk) {
this.mp.run(chunk);
}
onError(e) {
if (this.onErrorCallback != null) {
this.onErrorCallback(e);
}
}
}
module.exports = Client;

View File

@@ -1,69 +0,0 @@
'use strict';
const makeRequest = (exports.makeRequest = (method, params, id) => {
return JSON.stringify({
jsonrpc: '2.0',
method: method,
params: params,
id: id,
});
});
const createRecuesiveParser = (exports.createRecuesiveParser = (max_depth, delimiter) => {
const MAX_DEPTH = max_depth;
const DELIMITER = delimiter;
const recursiveParser = (n, buffer, callback) => {
if (buffer.length === 0) {
return { code: 0, buffer: buffer };
}
if (n > MAX_DEPTH) {
return { code: 1, buffer: buffer };
}
const xs = buffer.split(DELIMITER);
if (xs.length === 1) {
return { code: 0, buffer: buffer };
}
callback(xs.shift(), n);
return recursiveParser(n + 1, xs.join(DELIMITER), callback);
};
return recursiveParser;
});
const createPromiseResult = (exports.createPromiseResult = (resolve, reject) => {
return (err, result) => {
if (err) reject(err);
else resolve(result);
};
});
const createPromiseResultBatch = (exports.createPromiseResultBatch = (resolve, reject, argz) => {
return (err, result) => {
if (result && result[0] && result[0].id) {
// this is a batch request response
for (let r of result) {
r.param = argz[r.id];
}
}
if (err) reject(err);
else resolve(result);
};
});
class MessageParser {
constructor(callback) {
this.buffer = '';
this.callback = callback;
this.recursiveParser = createRecuesiveParser(20, '\n');
}
run(chunk) {
this.buffer += chunk;
while (true) {
const res = this.recursiveParser(0, this.buffer, this.callback);
this.buffer = res.buffer;
if (res.code === 0) {
break;
}
}
}
}
exports.MessageParser = MessageParser;

5850
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -1,34 +1,50 @@
{
"name": "@mempool/electrum-client",
"version": "1.1.8",
"description": "Electrum protocol client for React Native & Node.js",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"dependencies": {},
"devDependencies": {},
"repository": {
"type": "git",
"url": "git://github.com/mempool/electrum-client.git"
},
"bugs": {
"url": "https://github.com/mempool/electrum-client/issues"
"name": "@samouraiwallet/electrum-client",
"version": "1.2.0",
"engines": {
"node": ">=14.0.0"
},
"description": "Electrum protocol client for Node.js",
"keywords": [
"bitcoin",
"electrum",
"electrumx"
],
"engines": {
"node": ">=6"
"type": "module",
"exports": {
".": "./dist/index.js"
},
"contributors": [
{ "name": "Yuki Akiyama" },
{ "name": "7kharov" },
{ "name": "overtorment" },
{ "name": "janoside" },
{ "name": "softsimon" }
],
"license": "MIT"
"types": "./dist/index.d.ts",
"scripts": {
"test": "mocha",
"lint": "eslint --ext .ts src/",
"typescript": "tsc --noEmit",
"build:clean": "rm -rf dist",
"build:esm": "tsc -p tsconfig.build.json",
"build": "npm run build:clean && npm run build:esm",
"prepack": "npm run lint && npm run typescript && npm run test",
"prepare": "npm run build"
},
"repository": {
"type": "git",
"url": "git://code.samourai.io/dojo/electrum-client.git"
},
"bugs": {
"url": "https://code.samourai.io/dojo/electrum-client/-/issues"
},
"author": "Katana Cryptographic Ltd.",
"license": "LGPL-3.0",
"homepage": "https://code.samourai.io/dojo/electrum-client",
"devDependencies": {
"@types/mocha": "^9.1.0",
"@types/node": "^14.18.12",
"@typescript-eslint/eslint-plugin": "^5.12.1",
"@typescript-eslint/parser": "^5.12.1",
"eslint": "^8.10.0",
"eslint-plugin-import": "^2.25.4",
"eslint-plugin-unicorn": "^41.0.0",
"mocha": "^9.2.1",
"ts-node": "^10.5.0",
"typescript": "^4.5.5"
}
}

304
src/index.ts Normal file
View File

@@ -0,0 +1,304 @@
import {Client} from './lib/client.js'
import {
Callbacks,
ElectrumConfig,
ElectrumRequestBatchParams,
ElectrumRequestParams,
PersistencePolicy,
Protocol
} from './types'
export class ElectrumClient extends Client {
private onConnectCallback: ((client: ElectrumClient, versionInfo: [string, string]) => void) | null
private onCloseCallback: ((client: ElectrumClient) => void) | null
private onLogCallback: (str: string) => void
private timeLastCall: number
private persistencePolicy: Required<PersistencePolicy>
private electrumConfig: ElectrumConfig | null
private timeout: NodeJS.Timeout | null
versionInfo: [string, string]
constructor(port: number, host: string, protocol: Protocol, callbacks?: Callbacks) {
super(port, host, protocol, callbacks)
this.onConnectCallback = (callbacks && callbacks.onConnect) ? callbacks.onConnect : null
this.onCloseCallback = (callbacks && callbacks.onClose) ? callbacks.onClose : null
this.onLogCallback = (callbacks && callbacks.onLog) ? callbacks.onLog : (str: string) => {
console.log(str)
}
this.timeLastCall = 0
this.persistencePolicy = {
retryPeriod: 10000,
maxRetry: 1000,
pingPeriod: 120000,
callback: null,
}
this.electrumConfig = null
this.timeout = null
this.versionInfo = ['', '']
}
async initElectrum(electrumConfig: ElectrumConfig, persistencePolicy?: PersistencePolicy): Promise<ElectrumClient> {
this.persistencePolicy = {
...this.persistencePolicy,
...persistencePolicy
}
this.electrumConfig = electrumConfig
this.timeLastCall = 0
await this.connect()
this.versionInfo = (await this.server_version(this.electrumConfig?.client ?? '', this.electrumConfig?.version ?? ['', ''])) as [string, string]
if (this.onConnectCallback != null) {
this.onConnectCallback(this, this.versionInfo)
}
return this
}
// Override parent
protected async request(method: string, params: ElectrumRequestParams) {
this.timeLastCall = Date.now()
const response = await super.request(method, params)
this.keepAlive()
return response
}
protected async requestBatch(method: string, params: ElectrumRequestParams, secondParam?: ElectrumRequestBatchParams) {
this.timeLastCall = Date.now()
const response = await super.requestBatch(method, params, secondParam)
this.keepAlive()
return response
}
protected onClose(): void {
super.onClose()
const list = [
'server.peers.subscribe',
'blockchain.numblocks.subscribe',
'blockchain.headers.subscribe',
'blockchain.address.subscribe',
]
for (const event of list) this.subscribe.removeAllListeners(event)
let retryPeriod = 10000
if (this.persistencePolicy.retryPeriod > 0) {
retryPeriod = this.persistencePolicy.retryPeriod
}
if (this.onCloseCallback != null) {
this.onCloseCallback(this)
}
setTimeout(() => {
if (this.persistencePolicy.maxRetry > 0) {
this.reconnect().catch((error) => {
this.onError(error)
})
this.persistencePolicy.maxRetry -= 1
} else if (this.persistencePolicy.callback != null) {
this.persistencePolicy.callback()
}
}, retryPeriod)
}
// ElectrumX persistancy
private keepAlive(): void {
if (this.timeout != null) {
clearTimeout(this.timeout)
}
let pingPeriod = 120000
if (this.persistencePolicy.pingPeriod > 0) {
pingPeriod = this.persistencePolicy.pingPeriod
}
this.timeout = setTimeout(() => {
if (this.timeLastCall !== 0 && Date.now() > this.timeLastCall + pingPeriod) {
this.server_ping().catch((error) => {
this.log(`Keep-Alive ping failed: ${error}`)
})
}
}, pingPeriod)
}
close(): void {
super.close()
if (this.timeout != null) {
clearTimeout(this.timeout)
}
// eslint-disable-next-line no-multi-assign
this.reconnect = this.reconnect = this.onClose = this.keepAlive = () => Promise.resolve(this) // dirty hack to make it stop reconnecting
}
private reconnect(): Promise<ElectrumClient> {
this.log('Electrum attempting reconnect...')
this.initSocket()
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
return this.persistencePolicy == null ? this.initElectrum(this.electrumConfig!) : this.initElectrum(this.electrumConfig!, this.persistencePolicy)
}
private log(str: string): void {
this.onLogCallback(str)
}
// ElectrumX API
server_version(client_name: string, protocol_version: string[]) {
return this.request('server.version', [client_name, protocol_version])
}
server_banner() {
return this.request('server.banner', [])
}
server_features() {
return this.request('server.features', [])
}
server_ping() {
return this.request('server.ping', [])
}
server_addPeer(features: any) {
return this.request('server.add_peer', [features])
}
serverDonation_address() {
return this.request('server.donation_address', [])
}
serverPeers_subscribe() {
return this.request('server.peers.subscribe', [])
}
blockchainAddress_getProof(address: string) {
return this.request('blockchain.address.get_proof', [address])
}
blockchainScripthash_getBalance(scripthash: string) {
return this.request('blockchain.scripthash.get_balance', [scripthash])
}
blockchainScripthash_getBalanceBatch(scripthashes: string[]) {
return this.requestBatch('blockchain.scripthash.get_balance', scripthashes)
}
blockchainScripthash_listunspentBatch(scripthashes: string[]) {
return this.requestBatch('blockchain.scripthash.listunspent', scripthashes)
}
blockchainScripthash_getHistory(scripthash: string) {
return this.request('blockchain.scripthash.get_history', [scripthash])
}
blockchainScripthash_getHistoryBatch(scripthashes: string[]) {
return this.requestBatch('blockchain.scripthash.get_history', scripthashes)
}
blockchainScripthash_getMempool(scripthash: string) {
return this.request('blockchain.scripthash.get_mempool', [scripthash])
}
blockchainScripthash_listunspent(scripthash: string) {
return this.request('blockchain.scripthash.listunspent', [scripthash])
}
blockchainScripthash_subscribe(scripthash: string) {
return this.request('blockchain.scripthash.subscribe', [scripthash])
}
blockchainBlock_getHeader(height: number) {
return this.request('blockchain.block.get_header', [height])
}
blockchainBlock_headers(start_height: number, count: number) {
return this.request('blockchain.block.headers', [start_height, count])
}
blockchainEstimatefee(number: number) {
return this.request('blockchain.estimatefee', [number])
}
blockchainHeaders_subscribe(raw = false) {
return this.request('blockchain.headers.subscribe', [raw])
}
blockchain_relayfee() {
return this.request('blockchain.relayfee', [])
}
blockchainTransaction_broadcast(rawtx: string) {
return this.request('blockchain.transaction.broadcast', [rawtx])
}
blockchainTransaction_get(tx_hash: string, verbose = false) {
return this.request('blockchain.transaction.get', [tx_hash, verbose])
}
blockchainTransaction_getBatch(tx_hashes: string[], verbose = false) {
return this.requestBatch('blockchain.transaction.get', tx_hashes, verbose)
}
blockchainTransaction_getMerkle(tx_hash: string, height: number) {
return this.request('blockchain.transaction.get_merkle', [tx_hash, height])
}
mempool_getFeeHistogram() {
return this.request('mempool.get_fee_histogram', [])
}
// ---------------------------------
// protocol 1.1 deprecated method
// ---------------------------------
blockchainUtxo_getAddress(tx_hash: string, index: number) {
return this.request('blockchain.utxo.get_address', [tx_hash, index])
}
blockchainNumblocks_subscribe() {
return this.request('blockchain.numblocks.subscribe', [])
}
// ---------------------------------
// protocol 1.2 deprecated method
// ---------------------------------
blockchainBlock_getChunk(index: number) {
return this.request('blockchain.block.get_chunk', [index])
}
blockchainAddress_getBalance(address: string) {
return this.request('blockchain.address.get_balance', [address])
}
blockchainAddress_getHistory(address: string) {
return this.request('blockchain.address.get_history', [address])
}
blockchainAddress_getMempool(address: string) {
return this.request('blockchain.address.get_mempool', [address])
}
blockchainAddress_listunspent(address: string) {
return this.request('blockchain.address.listunspent', [address])
}
blockchainAddress_subscribe(address: string) {
return this.request('blockchain.address.subscribe', [address])
}
}

203
src/lib/client.ts Normal file
View File

@@ -0,0 +1,203 @@
import net from 'net'
import {EventEmitter} from 'events'
import {TlsSocketWrapper} from './tls-socket-wrapper.js'
import * as util from './util.js'
import {Protocol, Callbacks, ElectrumRequestBatchParams, ElectrumRequestParams} from '../types'
const TIMEOUT = 5000
export abstract class Client {
private id: number
private port: number
private host: string
private callback_message_queue: Map<number, (err: Error | null, result?: any) => void>
protected subscribe: EventEmitter
private mp: util.MessageParser
private conn: net.Socket | TlsSocketWrapper | null
private status: number
private protocol: Protocol
private onErrorCallback: ((e: Error) => void) | null
constructor(port: number, host: string, protocol: Protocol, callbacks?: Callbacks) {
this.id = 0
this.port = port
this.host = host
this.callback_message_queue = new Map()
this.subscribe = new EventEmitter()
this.mp = new util.MessageParser((body: string | undefined, n: number) => {
this.onMessage(body, n)
})
this.conn = null
this.status = 0
this.protocol = protocol // saving defaults
this.onErrorCallback = (callbacks && callbacks.onError) ? callbacks.onError : null
this.initSocket(protocol)
}
protected initSocket(protocol: Protocol = this.protocol): void {
switch (protocol) {
case 'tcp':
this.conn = new net.Socket()
break
case 'tls':
case 'ssl':
this.conn = new TlsSocketWrapper()
break
default:
throw new Error('unknown protocol')
}
this.conn.setTimeout(TIMEOUT)
this.conn.setEncoding('utf8')
this.conn.setKeepAlive(true, 0)
this.conn.setNoDelay(true)
this.conn.on('connect', () => {
this.conn && this.conn.setTimeout(0)
this.onConnect()
})
this.conn.on('close', () => {
this.onClose()
})
this.conn.on('data', (chunk: Buffer) => {
this.conn && this.conn.setTimeout(0)
this.onRecv(chunk)
})
this.conn.on('error', (e: Error) => {
this.onError(e)
})
this.status = 0
}
protected connect(): Promise<void> {
if (this.conn) {
if (this.status === 1) {
return Promise.resolve()
}
this.status = 1
return this.connectSocket(this.conn, this.port, this.host)
} else {
return Promise.reject(new Error('There is no socket to initialize connection on.'))
}
}
private connectSocket(conn: net.Socket | TlsSocketWrapper, port: number, host: string): Promise<void> {
return new Promise<void>((resolve, reject) => {
const errorHandler = (e: Error) => reject(e)
conn.on('error', errorHandler)
conn.connect(port, host, () => {
conn.removeListener('error', errorHandler)
resolve()
})
})
}
close(): void {
if (this.status === 0) {
return
}
this.conn && this.conn.end()
this.conn && this.conn.destroy()
this.status = 0
}
protected request(method: string, params: ElectrumRequestParams) {
if (this.status === 0) {
return Promise.reject(new Error('Connection to server lost, please retry'))
}
return new Promise((resolve, reject) => {
const id = ++this.id
const content = util.makeRequest(method, params, id)
this.callback_message_queue.set(id, util.createPromiseResult(resolve, reject))
this.conn && this.conn.write(`${content }\n`)
})
}
protected requestBatch(method: string, params: ElectrumRequestParams, secondParam: ElectrumRequestBatchParams) {
if (this.status === 0) {
return Promise.reject(new Error('Connection to server lost, please retry'))
}
return new Promise((resolve, reject) => {
const arguments_far_calls: Record<number, any> = {}
const contents = []
for (const param of params) {
const id = ++this.id
if (secondParam == null) {
contents.push(util.makeRequest(method, [param], id))
} else {
contents.push(util.makeRequest(method, [param, secondParam], id))
}
arguments_far_calls[id] = param
}
const content = `[${ contents.join(',') }]`
this.callback_message_queue.set(this.id, util.createPromiseResultBatch(resolve, reject, arguments_far_calls))
// callback will exist only for max id
this.conn && this.conn.write(`${content }\n`)
})
}
private response(msg: any) { // FIXME
let callback
if (!msg.id && msg[0] && msg[0].id) {
// this is a response from batch request
for (const m of msg) {
if (m.id && this.callback_message_queue.has(m.id)) {
callback = this.callback_message_queue.get(m.id)
this.callback_message_queue.delete(m.id)
}
}
} else {
callback = this.callback_message_queue.get(msg.id)
}
if (callback) {
this.callback_message_queue.delete(msg.id)
if (msg.error) {
callback(msg.error)
} else {
callback(null, msg.result || msg)
}
} else {
console.log(msg)
throw new Error('Error getting callback while handling response')
}
}
private onMessage(body: string | undefined, n: number): void {
const msg = JSON.parse(body || '')
if (Array.isArray(msg)) {
this.response(msg)
} else if (msg.id == null) {
this.subscribe.emit(msg.method, msg.params)
} else {
this.response(msg)
}
}
// eslint-disable-next-line @typescript-eslint/no-empty-function
private onConnect(): void {}
protected onClose(): void {
this.status = 0
for (const [key, fn] of this.callback_message_queue.entries()) {
fn(new Error('close connect'))
this.callback_message_queue.delete(key)
}
}
private onRecv(chunk: Buffer): void {
this.mp.run(chunk)
}
protected onError(e: Error): void {
if (this.onErrorCallback != null) {
this.onErrorCallback(e)
}
}
}

View File

@@ -0,0 +1,92 @@
import tls, {TLSSocket} from 'tls'
import {EventEmitter} from 'events'
/**
* Simple wrapper to mimick Socket class from NET package, since TLS package has slightly different API.
* We implement several methods that TCP sockets are expected to have. We will proxy call them as soon as
* real TLS socket will be created (TLS socket created after connection).
*/
export class TlsSocketWrapper extends EventEmitter {
private _socket: TLSSocket | null
private _timeout: number
private _encoding: BufferEncoding
private _keepAliveEneblad: boolean
private _keepAliveinitialDelay: number
private _noDelay: boolean
constructor() {
super()
this._socket = null
// defaults:
this._timeout = 5000
this._encoding = 'utf8'
this._keepAliveEneblad = true
this._keepAliveinitialDelay = 0
this._noDelay = true
}
setTimeout(timeout: number) {
if (this._socket) this._socket.setTimeout(timeout)
this._timeout = timeout
}
setEncoding(encoding: BufferEncoding) {
if (this._socket) this._socket.setEncoding(encoding)
this._encoding = encoding
}
setKeepAlive(enabled: boolean, initialDelay: number) {
if (this._socket) this._socket.setKeepAlive(enabled, initialDelay)
this._keepAliveEneblad = enabled
this._keepAliveinitialDelay = initialDelay
}
setNoDelay(noDelay: boolean) {
if (this._socket) this._socket.setNoDelay(noDelay)
this._noDelay = noDelay
}
connect(port: number, host: string, callback: () => void) {
// resulting TLSSocket extends <net.Socket>
this._socket = tls.connect({ port: port, host: host, rejectUnauthorized: false }, () => {
return callback()
})
// setting everything that was set to this proxy class
this._socket.setTimeout(this._timeout)
this._socket.setEncoding(this._encoding)
this._socket.setKeepAlive(this._keepAliveEneblad, this._keepAliveinitialDelay)
this._socket.setNoDelay(this._noDelay)
// resubscribing to events on newly created socket so we could proxy them to already established listeners
this._socket.on('data', data => {
this.emit('data', data)
})
this._socket.on('error', data => {
this.emit('error', data)
})
this._socket.on('close', data => {
this.emit('close', data)
})
this._socket.on('connect', data => {
this.emit('connect', data)
})
this._socket.on('connection', data => {
this.emit('connection', data)
})
}
end() {
this._socket && this._socket.end()
}
destroy() {
this._socket && this._socket.destroy()
}
write(data: string | Uint8Array) {
this._socket && this._socket.write(data)
}
}

76
src/lib/util.ts Normal file
View File

@@ -0,0 +1,76 @@
import {ElectrumRequestParams} from '../types'
export const makeRequest = (method: string, params: ElectrumRequestParams, id: number) => {
return JSON.stringify({
jsonrpc: '2.0',
method: method,
params: params,
id: id,
})
}
export const createRecursiveParser = (max_depth: number, delimiter: string) => {
const MAX_DEPTH = max_depth
const DELIMITER = delimiter
const recursiveParser = (n: number, buffer: string, callback: (xs: string | undefined, n: number) => void): { code: number, buffer: string } => {
if (buffer.length === 0) {
return {code: 0, buffer: buffer}
}
if (n > MAX_DEPTH) {
return {code: 1, buffer: buffer}
}
const xs = buffer.split(DELIMITER)
if (xs.length === 1) {
return {code: 0, buffer: buffer}
}
callback(xs.shift(), n)
return recursiveParser(n + 1, xs.join(DELIMITER), callback)
}
return recursiveParser
}
export const createPromiseResult = (resolve: (value?: any) => void, reject: (reason?: any) => void) => {
return (err: Error | null, result?: any) => {
if (err) reject(err)
else resolve(result)
}
}
export const createPromiseResultBatch = (resolve: (value?: any) => void, reject: (reason?: any) => void, argz: Record<number, any>) => {
return (err: Error | null, result?: Array<any>) => {
if (result && result[0] && result[0].id) {
// this is a batch request response
for (const r of result) {
r.param = argz[r.id]
}
}
if (err) reject(err)
else resolve(result)
}
}
type MessageParserCallback = (body: string | undefined, n: number) => void;
export class MessageParser {
private buffer: string
private callback: MessageParserCallback
private recursiveParser = createRecursiveParser(20, '\n')
constructor(callback: MessageParserCallback) {
this.buffer = ''
this.callback = callback
this.recursiveParser = createRecursiveParser(20, '\n')
}
run(chunk: Buffer) {
this.buffer += chunk
/* eslint-disable-next-line no-constant-condition */
while (true) {
const res = this.recursiveParser(0, this.buffer, this.callback)
this.buffer = res.buffer
if (res.code === 0) {
break
}
}
}
}

26
src/types/index.ts Normal file
View File

@@ -0,0 +1,26 @@
import {ElectrumClient} from '../index.js'
export type Protocol = 'tcp' | 'tls' | 'ssl';
export type Callbacks = {
onConnect?: (client: ElectrumClient, versionInfo: [string, string]) => void;
onClose?: (client: ElectrumClient) => void;
onLog?: (str: string) => void;
onError?: (e: Error) => void;
}
export type PersistencePolicy = {
retryPeriod?: number,
maxRetry?: number,
pingPeriod?: number,
callback?: (() => void) | null
}
export type ElectrumConfig = {
client: string;
version: string[];
}
export type ElectrumRequestParams = Array<number | string | boolean | Array<any>>;
export type ElectrumRequestBatchParams = number | string | boolean | undefined;

106
test/index.test.ts Normal file
View File

@@ -0,0 +1,106 @@
/* eslint-disable max-len, @typescript-eslint/ban-ts-comment */
import assert from 'assert'
import {ElectrumClient} from '../src'
let tcpClient: ElectrumClient
let tlsClient: ElectrumClient
/*
const callbacks = {
onConnect: (_: any, versionInfo: any) => {
console.log('client connect', versionInfo)
},
onLog: (msg: any) => {
console.log('client log', msg)
},
onError: (err: any) => {
console.error('client error', err)
},
onClose: () => {
console.log('client: Connection closed')
}
}
*/
before(() => {
tcpClient = new ElectrumClient(60001, 'btc.electroncash.dk', 'tcp')
tlsClient = new ElectrumClient(60002, 'btc.electroncash.dk', 'tls')
})
after(() => {
tcpClient.close()
tlsClient.close()
})
describe('ElectrumClient TCP', () => {
it('successfully connects to Electrum server', async () => {
const clt = await tcpClient.initElectrum({client: 'electrum-client-js', version: ['1.2', '1.4']}, { retryPeriod: 2000 })
assert.ok(clt.versionInfo)
})
it('successfully makes a standard request', async () => {
const response = await tcpClient.blockchainTransaction_get('b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a')
assert.strictEqual(response, '02000000016016c6d039cbdeefa655e4b5ac61ec2b5fe16920529f086a2439f59a5994bed6200000006a4730440220421b5daf5f72e514075d256121d6b66e1d9a8993d37ceb0532baca11f6964da502205333d1c4b9be749180bfa8da4da6a07c0e9e2d853c809a75c4b60ef717a628b20121029139c783aa8f31707a67248a6a6b643855e9d1484dbd53cfe7d9e3adf3ce7098ffffffff02c19a01000000000017a9146eda8b447af853746f04b902fea5b2cd959d866d87692c0200000000001976a914443674ce759f8fa2fe83a6608339da782b890c1988ac00000000')
})
it('successfully makes a batch request', async () => {
const response = await tcpClient.blockchainTransaction_getBatch(['b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a', 'f08474320cb16c34bb6ccbd8ca77b41168589155e8cf0af787d8d8b2a975af0b'])
assert.deepStrictEqual(response, [{
id: 3,
jsonrpc: '2.0',
param: 'b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a',
result: '02000000016016c6d039cbdeefa655e4b5ac61ec2b5fe16920529f086a2439f59a5994bed6200000006a4730440220421b5daf5f72e514075d256121d6b66e1d9a8993d37ceb0532baca11f6964da502205333d1c4b9be749180bfa8da4da6a07c0e9e2d853c809a75c4b60ef717a628b20121029139c783aa8f31707a67248a6a6b643855e9d1484dbd53cfe7d9e3adf3ce7098ffffffff02c19a01000000000017a9146eda8b447af853746f04b902fea5b2cd959d866d87692c0200000000001976a914443674ce759f8fa2fe83a6608339da782b890c1988ac00000000'
},
{
id: 4,
jsonrpc: '2.0',
param: 'f08474320cb16c34bb6ccbd8ca77b41168589155e8cf0af787d8d8b2a975af0b',
result: '01000000000101536c64334a7e7c49713d836ef9230054e6c38b8c086a3e2068d054781aae89050100000000ffffffff025d9200000000000017a91415035c6225abdf351aa90e6a60726f5e2653839f8728751900000000002200209054b26aafa22ff9bff790d0ed9cc9c84079d7e237e1b617042df9a9734d8aec0400473044022059913f1526f2bfd5a236f86ada8f68b4943632ef9d306d44e482935774059aa60220360d783ca765299c114e28dd0304df913315e5297d9f78fd89319c1ddc6177260147304402204a135548f460dd96e3ea7f981c69d52773cec1475c278631a2180a8010b5dd7802206e090c9c6b1734a9757c76f9a1d5e576bf7b805d12e2d50d344800628dde4f420147522102254d4655d0cae8ad2d96a6789d08ac63982171f10795a5146d03a8369ffd51b921029009039142b4de669fe67507bb3a6b17ff38f7798ae4d7bb3826a3cc2527d62252ae00000000'
}])
})
it('should make a request after reconnection', (done) => {
// @ts-ignore Hijack Typescript to call method on private field in order to simulate connection close
tcpClient.conn?.end()
setTimeout(async () => {
const res = await tcpClient.server_banner()
assert.ok(res)
done()
}, 5000)
})
})
describe('ElectrumClient TLS', () => {
it('successfully connects to Electrum server', async () => {
const clt = await tlsClient.initElectrum({client: 'electrum-client-js', version: ['1.2', '1.4']})
assert.ok(clt.versionInfo)
})
it('successfully makes a standard request', async () => {
const response = await tlsClient.blockchainTransaction_get('b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a')
assert.strictEqual(response, '02000000016016c6d039cbdeefa655e4b5ac61ec2b5fe16920529f086a2439f59a5994bed6200000006a4730440220421b5daf5f72e514075d256121d6b66e1d9a8993d37ceb0532baca11f6964da502205333d1c4b9be749180bfa8da4da6a07c0e9e2d853c809a75c4b60ef717a628b20121029139c783aa8f31707a67248a6a6b643855e9d1484dbd53cfe7d9e3adf3ce7098ffffffff02c19a01000000000017a9146eda8b447af853746f04b902fea5b2cd959d866d87692c0200000000001976a914443674ce759f8fa2fe83a6608339da782b890c1988ac00000000')
})
it('successfully makes a batch request', async () => {
const response = await tlsClient.blockchainTransaction_getBatch(['b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a', 'f08474320cb16c34bb6ccbd8ca77b41168589155e8cf0af787d8d8b2a975af0b'])
assert.deepStrictEqual(response, [{
id: 3,
jsonrpc: '2.0',
param: 'b270b8a113c048ed0024e470e3c7794565c2b3e18c600d20410ec8f454b7d25a',
result: '02000000016016c6d039cbdeefa655e4b5ac61ec2b5fe16920529f086a2439f59a5994bed6200000006a4730440220421b5daf5f72e514075d256121d6b66e1d9a8993d37ceb0532baca11f6964da502205333d1c4b9be749180bfa8da4da6a07c0e9e2d853c809a75c4b60ef717a628b20121029139c783aa8f31707a67248a6a6b643855e9d1484dbd53cfe7d9e3adf3ce7098ffffffff02c19a01000000000017a9146eda8b447af853746f04b902fea5b2cd959d866d87692c0200000000001976a914443674ce759f8fa2fe83a6608339da782b890c1988ac00000000'
},
{
id: 4,
jsonrpc: '2.0',
param: 'f08474320cb16c34bb6ccbd8ca77b41168589155e8cf0af787d8d8b2a975af0b',
result: '01000000000101536c64334a7e7c49713d836ef9230054e6c38b8c086a3e2068d054781aae89050100000000ffffffff025d9200000000000017a91415035c6225abdf351aa90e6a60726f5e2653839f8728751900000000002200209054b26aafa22ff9bff790d0ed9cc9c84079d7e237e1b617042df9a9734d8aec0400473044022059913f1526f2bfd5a236f86ada8f68b4943632ef9d306d44e482935774059aa60220360d783ca765299c114e28dd0304df913315e5297d9f78fd89319c1ddc6177260147304402204a135548f460dd96e3ea7f981c69d52773cec1475c278631a2180a8010b5dd7802206e090c9c6b1734a9757c76f9a1d5e576bf7b805d12e2d50d344800628dde4f420147522102254d4655d0cae8ad2d96a6789d08ac63982171f10795a5146d03a8369ffd51b921029009039142b4de669fe67507bb3a6b17ff38f7798ae4d7bb3826a3cc2527d62252ae00000000'
}])
})
})

13
test/lib/util.test.ts Normal file
View File

@@ -0,0 +1,13 @@
import assert from 'assert'
import * as util from '../../src/lib/util.js'
describe('util package', () => {
describe('makeRequest()', () => {
it('should make a correct request payload', () => {
const expected = '{"jsonrpc":"2.0","method":"testMethod","params":["stringParam",1,true],"id":1}'
const request = util.makeRequest('testMethod', ['stringParam', 1, true], 1)
assert.strictEqual(request, expected)
})
})
})

10
tsconfig.build.json Normal file
View File

@@ -0,0 +1,10 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src"
},
"exclude": [
"test"
]
}

82
tsconfig.json Normal file
View File

@@ -0,0 +1,82 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "es2020", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
"allowJs": false, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
"declaration": true, /* Generates corresponding '.d.ts' file. */
"declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
"sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./dist", /* Redirect output structure to the directory. */
"rootDir": ".", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
"removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
"isolatedModules": false, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
"noEmitOnError": true,
"resolveJsonModule": true,
"stripInternal": true,
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
"strictNullChecks": true, /* Enable strict null checks. */
"strictFunctionTypes": true, /* Enable strict checking of function types. */
"strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
"strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
"noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
"alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
"noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
"noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
"noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
"allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": false, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
},
"exclude": [
"node_modules",
"dist",
],
"include": [
"src",
"test"
]
}