forked from alexbosworth/balanceofsatoshis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathopen_channel.js
390 lines (332 loc) · 11.8 KB
/
open_channel.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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
const {addPeer} = require('ln-service');
const asyncAuto = require('async/auto');
const asyncDetectSeries = require('async/detectSeries');
const asyncReflect = require('async/reflect');
const asyncTimeout = require('async/timeout');
const {getChainFeeRate} = require('ln-service');
const {getChannels} = require('ln-service');
const {getClosedChannels} = require('ln-service');
const {getIdentity} = require('ln-service');
const {getNetwork} = require('ln-sync');
const {getNode} = require('ln-service');
const {getPeers} = require('ln-service');
const {getPendingChannels} = require('ln-service');
const {getSeedNodes} = require('ln-sync');
const {openChannel} = require('ln-service');
const {returnResult} = require('asyncjs-util');
const adjustFees = require('./../routing/adjust_fees');
const connectToPeer = require('./../peers/connect_to_peer');
const {getMempoolSize} = require('./../chain');
const {getPastForwards} = require('./../routing');
const peersWithActivity = require('./peers_with_activity');
const {shuffle} = require('./../arrays');
const asBigTok = tokens => (tokens / 1e8).toFixed(8);
const channelTokens = 5e6;
const connectTimeout = 1000 * 30;
const days = 90;
const defaultDescription = 'bos increase-outbound-liquidity';
const fastConf = 6;
const {floor} = Math;
const getMempoolRetries = 10;
const maxMempoolSize = 2e6;
const minOutbound = 4294967;
const minForwarded = 1e5;
const numericFeeRate = n => !!n && /^\d+$/.test(n) ? Number(n) : undefined;
const regularConf = 72;
const slowConf = 144;
/** Open up a new channel
{
[chain_fee_rate]: <Chain Fee Tokens Per VByte to Pay Number>
[is_dry_run]: <Avoid Actually Opening a New Channel Bool>
[is_private]: <Mark Channel as Private Booll>
lnd: <Authenticated LND gRPC API Object>
logger: <Winston Logger Object>
[peer]: <Peer Public Key Hex String>
request: <Request Function>
[set_fee_rate]: <Fee Rate String>
[tokens]: <Tokens for New Channel Number>
}
@returns via cbk or Promise
*/
module.exports = (args, cbk) => {
return new Promise((resolve, reject) => {
return asyncAuto({
// Check arguments
validate: cbk => {
if (!args.lnd) {
return cbk([400, 'ExpectedLndObjectToOpenNewChannel']);
}
if (!args.logger) {
return cbk([400, 'ExpectedLoggerObjectToOpenNewChannel']);
}
if (!args.request) {
return cbk([400, 'ExpectedRequestFunctionToOpenNewChannel']);
}
if (args.tokens === 0) {
return cbk([400, 'ExpectedTokensValueToOpenNewChannel']);
}
return cbk();
},
// Get channels
getChannels: ['validate', ({}, cbk) => {
return getChannels({lnd: args.lnd}, cbk);
}],
// Get closed channels
getClosed: ['validate', ({}, cbk) => {
return getClosedChannels({lnd: args.lnd}, cbk);
}],
// Get fast fee rate
getFastFee: ['validate', ({}, cbk) => {
return getChainFeeRate({
confirmation_target: fastConf,
lnd: args.lnd,
},
cbk);
}],
// Get forwards
getForwards: ['validate', ({}, cbk) => {
return getPastForwards({days, lnd: args.lnd}, cbk);
}],
// Get network
getNetwork: ['validate', ({}, cbk) => {
return getNetwork({lnd: args.lnd}, cbk);
}],
// Get normal fee rate
getNormalFee: ['validate', ({}, cbk) => {
return getChainFeeRate({
confirmation_target: regularConf,
lnd: args.lnd,
},
cbk);
}],
// Get connected peers
getPeers: ['validate', ({}, cbk) => getPeers({lnd: args.lnd}, cbk)],
// Get pending channels
getPending: ['validate', ({}, cbk) => {
return getPendingChannels({lnd: args.lnd}, cbk);
}],
// Get low fee rate
getSlowFee: ['validate', ({}, cbk) => {
return getChainFeeRate({
confirmation_target: slowConf,
lnd: args.lnd,
},
cbk);
}],
// Get wallet identity
getWallet: ['validate', ({}, cbk) => getIdentity({lnd: args.lnd}, cbk)],
// Get mempool size
getMempool: ['getNetwork', ({getNetwork}, cbk) => {
return getMempoolSize({
network: getNetwork.network,
request: args.request,
retries: getMempoolRetries,
},
cbk);
}],
// Get seed nodes
getSeed: ['getNetwork', asyncReflect(({getNetwork}, cbk) => {
// Exit early when a peer is specified
if (!!args.peer) {
return cbk(null, {nodes: []});
}
return getSeedNodes({
network: getNetwork.network,
request: args.request,
},
cbk);
})],
// Candidate peers
candidates: [
'getChannels',
'getClosed',
'getPending',
'getForwards',
'getSeed',
({getChannels, getClosed, getForwards, getPending, getSeed}, cbk) =>
{
const allChannels = []
.concat(getChannels.channels)
.concat(getPending.pending_channels.filter(n => !!n.is_opening));
const {peers} = peersWithActivity({
additions: [].concat(args.peer).filter(n => !!n),
channels: allChannels,
forwards: getForwards.forwards,
terminated: getClosed.channels,
});
// Exit early when a peer is specified
if (!!args.peer) {
return cbk(null, peers.filter(n => n.public_key === args.peer));
}
const depletedPeers = peers
.filter(n => n.outbound < minOutbound) // Depleted
.filter(n => n.forwarded > minForwarded); // Previous forwards
const seeded = !!getSeed.value ? getSeed.value.nodes : [];
const scorePeers = peersWithActivity({
additions: seeded.map(n => n.public_key),
channels: allChannels,
forwards: getForwards.forwards,
terminated: getClosed.channels,
});
const untriedPeers = scorePeers.peers
.filter(peer => !peer.outbound)
.filter(peer => {
const previous = getClosed.channels.find(n => {
return peer.public_key === n.partner_public_key;
});
return !previous;
});
return cbk(null, [].concat(depletedPeers).concat(untriedPeers));
}],
// Check if the chain fee rate is high
checkChainFees: [
'getFastFee',
'getMempool',
'getNormalFee',
'getSlowFee',
({getFastFee, getMempool, getNormalFee, getSlowFee}, cbk) =>
{
if (!!args.chain_fee_rate) {
return cbk();
}
const fastFee = getFastFee.tokens_per_vbyte;
const feeRate = getNormalFee.tokens_per_vbyte;
const slowFee = getSlowFee.tokens_per_vbyte;
const estimateRatio = fastFee / slowFee;
const vbytesRatio = (getMempool.vbytes || Number()) / maxMempoolSize;
if (!!floor(estimateRatio) && !!floor(vbytesRatio)) {
return cbk([503, 'FeeRateIsHighNow', {needed_fee_rate: feeRate}]);
}
return cbk();
}],
// Select a peer and open a channel
openChannel: [
'candidates',
'checkChainFees',
'getNormalFee',
'getPeers',
'getWallet',
({candidates, getNormalFee, getPeers, getWallet}, cbk) =>
{
if (!candidates.length) {
return cbk([404, 'NoObviousCandidateForNewChannel']);
}
const hasPeer = !!getPeers.peers.find(n => n.public_key === args.peer);
// Find peer that can be connected to
return asyncDetectSeries(
shuffle({array: candidates}).shuffled,
(candidate, cbk) => {
// Exit early when the candidate is self
if (candidate.public_key === getWallet.public_key) {
return cbk(null, false);
}
return getNode({
is_omitting_channels: true,
lnd: args.lnd,
public_key: candidate.public_key,
},
(err, res) => {
// Ignore errors when node is unknown
const sockets = !!res ? res.sockets : [];
// Exit early when there is no socket to connect to
if (!sockets.length && !hasPeer) {
return cbk(null, false);
}
const node = {
alias: !!res && !!res.alias ? res.alias : undefined,
past_forwarded: asBigTok(candidate.forwarded),
current_inbound: asBigTok(candidate.inbound),
current_outbound: asBigTok(candidate.outbound),
public_key: candidate.public_key,
};
args.logger.info({
evaluating: `${node.alias || String()} ${node.public_key}`,
});
return connectToPeer({
id: node.public_key,
lnd: args.lnd,
logger: args.logger,
sockets: sockets.map(n => n.socket),
},
err => {
if (!!err && !hasPeer) {
return cbk(null, false);
}
const normalFee = getNormalFee.tokens_per_vbyte;
const feeRate = args.chain_fee_rate || normalFee;
// Exit early when this is a dry run
if (!!args.is_dry_run) {
args.logger.info({
opening_with: node,
chain_fee_tokens_per_vbyte: feeRate,
is_dry_run: true,
new_channel_size: asBigTok(args.tokens || channelTokens),
});
return cbk(null, true);
}
return openChannel({
chain_fee_tokens_per_vbyte: feeRate,
description: defaultDescription,
fee_rate: numericFeeRate(args.set_fee_rate),
is_private: args.is_private,
lnd: args.lnd,
local_tokens: args.tokens || channelTokens,
partner_public_key: node.public_key,
},
(err, res) => {
const [, code] = err || [];
// Exit early when there is not enough balance
if (code === 'InsufficientFundsToCreateChannel') {
return cbk(err);
}
// Exit early when there is only one candidate
if (!!err && !!args.peer) {
return cbk(err);
}
// Channel open failure, try a different peer
if (!!err) {
return cbk(null, false);
}
args.logger.info({
opening_with: node,
chain_fee_tokens_per_vbyte: feeRate,
transaction_id: res.transaction_id,
new_channel_size: asBigTok(args.tokens || channelTokens),
is_private: args.is_private || undefined,
});
return cbk(null, true);
});
});
});
},
(err, selected) => {
if (!!err) {
return cbk(err);
}
if (!selected) {
return cbk([400, 'FailedToConnectToAnyCandidatePeer']);
}
return cbk(null, selected);
},
);
}],
// Set fee rate
setFeeRate: ['openChannel', ({openChannel}, cbk) => {
// Exit early when not specifying fee rates
if (!args.set_fee_rate) {
return cbk();
}
return adjustFees({
cltv_delta: undefined,
fee_rate: args.set_fee_rate,
fs: args.fs,
lnd: args.lnd,
logger: args.logger,
to: [openChannel.public_key],
},
cbk);
}],
},
returnResult({reject, resolve}, cbk));
});
};