forked from Ride-The-Lightning/c-lightning-REST
-
Notifications
You must be signed in to change notification settings - Fork 0
/
lightning-client-js.js
173 lines (143 loc) · 6.01 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
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
//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 fs = require('fs');
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')
, fStat = (...p) => fs.statSync(path.join(...p))
, fExists = (...p) => fs.existsSync(path.join(...p));
let somedata = '';
class LightningClient extends EventEmitter {
constructor(rpcPath=defaultRpcPath) {
global.logger.log("rpcPath -> " + rpcPath);
if (!path.isAbsolute(rpcPath)) {
throw new Error('The rpcPath must be an absolute path');
}
if (!fExists(rpcPath) || !fStat(rpcPath).isSocket()){
// network directory provided, use the lightning-rpc within it
if (fExists(rpcPath, 'lightning-rpc')) {
rpcPath = path.join(rpcPath, 'lightning-rpc');
}
// main data directory provided, default to using the bitcoin mainnet subdirectory
else if (fExists(rpcPath, 'bitcoin', 'lightning-rpc')) {
global.logger.error(`WARN: ${rpcPath}/lightning-rpc is missing, using the bitcoin mainnet subdirectory at ${rpcPath}/bitcoin instead.`)
rpcPath = path.join(rpcPath, 'bitcoin', 'lightning-rpc')
}
// or using the bitcoin testnet subdirectory
else if (fExists(rpcPath, 'testnet', 'lightning-rpc')) {
global.logger.error(`WARN: ${rpcPath}/lightning-rpc is missing, using the bitcoin testnet subdirectory at ${rpcPath}/testnet instead.`)
rpcPath = path.join(rpcPath, 'testnet', 'lightning-rpc')
}
// or using the bitcoin signet subdirectory
else if (fExists(rpcPath, 'signet', 'lightning-rpc')) {
global.logger.error(`WARN: ${rpcPath}/lightning-rpc is missing, using the bitcoin signet subdirectory at ${rpcPath}/signet instead.`)
rpcPath = path.join(rpcPath, 'signet', 'lightning-rpc')
}
// or using the bitcoin regtest subdirectory
else if (fExists(rpcPath, 'regtest', 'lightning-rpc')){
global.logger.error(`WARN: ${rpcPath}/lightning-rpc is missing, using the bitcoin regtest subdirectory at ${rpcPath}/regtest instead.`)
rpcPath = path.join(rpcPath, 'regtest', 'lightning-rpc')
}
}
global.logger.log(`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', () => {
global.logger.log(`Lightning client connected`);
_self.reconnectWait = 1;
resolve();
});
_self.client.on('end', () => {
console.log('Lightning client connection closed');
});
_self.client.on('error', error => {
global.logger.error(`Lightning client connection error`, error);
_self.emit('error', error);
_self.increaseWaitTime();
_self.reconnect();
});
});
this.client.on('data', data => _self._handledata(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(() => {
global.logger.log('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 = {
jsonrpc: "2.0",
method,
params: args,
id: ''+callInt
};
//global.logger.log('#%d --> %s', callInt, method);
//global.logger.log(args);
// Wait for the client to connect
return this.clientConnectionPromise
.then(() => new Promise((resolve, reject) => {
// Send the command
_self.client.write(JSON.stringify(sendObj));
// Wait for a response
this.once('res:' + callInt, res => res.error == null
? resolve(res.result)
: reject(LightningError(res.error))
);
}));
}
_handledata(data) {
if (typeof global.REST_PLUGIN_CONFIG === 'undefined') {
this.parser.write(data)
} else {
if(data.length && data.length > 0) {
somedata += data
}
if (somedata.length > 1 && somedata.slice(-2) === "\n\n") {
this.parser.write(somedata)
somedata = ''
}
}
}
}
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;