forked from Ride-The-Lightning/c-lightning-REST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightning-client-js.js
128 lines (102 loc) · 3.8 KB
/
lightning-client-js.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
//Credit to Shesek for "github:shesek/lightning-client-js".
//This is the main library, which enables connection with the c-lightning node
'use strict';
const path = require('path');
const net = require('net');
const debug = require('debug')('lightning-client');
const {EventEmitter} = require('events');
const JSONParser = require('jsonparse')
const LightningError = require('error/typed')({ type: 'lightning', message: 'lightning-client error' })
const methods = require('./methods');
const defaultRpcPath = path.join(require('os').homedir(), '.lightning')
class LightningClient extends EventEmitter {
constructor(rpcPath=defaultRpcPath) {
if (!path.isAbsolute(rpcPath)) {
throw new Error('The rpcPath must be an absolute path');
}
if (rpcPath.slice(-14) !== '/lightning-rpc') {
rpcPath = path.join(rpcPath, '/lightning-rpc');
}
debug(`Connecting to ${rpcPath}`);
super();
this.rpcPath = rpcPath;
this.reconnectWait = 0.5;
this.reconnectTimeout = null;
this.reqcount = 0;
this.parser = new JSONParser
const _self = this;
this.client = net.createConnection(rpcPath);
this.clientConnectionPromise = new Promise(resolve => {
_self.client.on('connect', () => {
debug(`Lightning client connected`);
_self.reconnectWait = 1;
resolve();
});
_self.client.on('end', () => {
console.error('Lightning client connection closed, reconnecting');
_self.increaseWaitTime();
_self.reconnect();
});
_self.client.on('error', error => {
console.error(`Lightning client connection error`, error);
_self.emit('error', error);
_self.increaseWaitTime();
_self.reconnect();
});
});
this.client.on('data', data => _self.parser.write(data));
this.parser.onValue = function(val) {
if (this.stack.length) return; // top-level objects only
debug('#%d <-- %O', val.id, val.error || val.result)
_self.emit('res:' + val.id, val);
}
}
increaseWaitTime() {
if (this.reconnectWait >= 16) {
this.reconnectWait = 16;
} else {
this.reconnectWait *= 2;
}
}
reconnect() {
const _self = this;
if (this.reconnectTimeout) {
return;
}
this.reconnectTimeout = setTimeout(() => {
debug('Trying to reconnect...');
_self.client.connect(_self.rpcPath);
_self.reconnectTimeout = null;
}, this.reconnectWait * 1000);
}
call(method, args = []) {
const _self = this;
const callInt = ++this.reqcount;
const sendObj = {
method,
params: args,
id: ''+callInt
};
debug('#%d --> %s %o', callInt, method, args)
// Wait for the client to connect
return this.clientConnectionPromise
.then(() => new Promise((resolve, reject) => {
// Wait for a response
this.once('res:' + callInt, res => res.error == null
? resolve(res.result)
: reject(LightningError(res.error))
);
// Send the command
_self.client.write(JSON.stringify(sendObj));
}));
}
}
const protify = s => s.replace(/-([a-z])/g, m => m[1].toUpperCase());
methods.forEach(k => {
LightningClient.prototype[protify(k)] = function (...args) {
return this.call(k, args);
};
});
module.exports = rpcPath => new LightningClient(rpcPath);
module.exports.LightningClient = LightningClient;
module.exports.LightningError = LightningError;