This repository has been archived by the owner on Jul 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathLN-Channel-Opener.js
245 lines (211 loc) · 6.57 KB
/
LN-Channel-Opener.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
'use strict'
const Db = require('./src/DB/DB')
const Order = require('./src/Orders/Order')
const config = require('./config/server.json')
const async = require('async')
const { Client: GrenacheClient } = require('blocktank-worker')
const { lnWorker, callWorker } = require('./src/util/common-workers')
const { find } = require('lodash')
const {parseChannelOpenErr, chanErrors: errors} = require("./src/util/channel-opening-errors")
console.log('Starting Channel Opener...')
const MAX_CHANNEL_OPEN_ATTEMPT = config.constants.max_attempt_channel_open
const MAX_CHAN_FEE = 200
Db((err) => {
if (err) throw err
console.log('Started database')
})
async function getPaidOrders () {
const db = await Db()
return db.LnChannelOrders.find({
state: Order.ORDER_STATES.URI_SET,
created_at: { $gte: Date.now() - 172800000 }
}).limit(10000000).toArray()
}
async function getProducts (productIds) {
const db = await Db()
return db.Inventory.find({ _id: { $in: productIds } }).toArray()
}
async function updateOrders (orders) {
const logInfo = []
const update = await Promise.all(orders.map(async ({ order, result }) => {
result.ts = Date.now()
let state
if (order.order_result.length === MAX_CHANNEL_OPEN_ATTEMPT || result.giveup) {
// GIVE UP OPENING CHANNEL
// Tried too many times or node has issues
state = Order.ORDER_STATES.GIVE_UP
order.order_result.push(result)
log.push([
order._id,
"gave up",
result
])
} else if (result.channel_tx && result.channel_tx.transaction_id) {
// CHANNEL IS OPENING
state = Order.ORDER_STATES.OPENING
order.channel_open_tx = result.channel_tx
alert('info', `Opening Channel: ${order._id} - txid: ${JSON.stringify(result.channel_tx, null, 2)}`)
} else {
if (order.order_result.length === 0 || order.order_result[order.order_result.length - 1].channel_error !== result.channel_error) {
order.order_result.push(result)
} else {
order.order_result[order.order_result.length - 1] = result
}
log.push([
order._id,
"retry",
result
])
state = order.state
}
if (result.error) {
console.log('Failing to open channel: ', order._id)
}
await Order.updateOrder(order._id, {
state,
order_result: order.order_result,
channel_open_tx: order.channel_open_tx
})
}))
//alert("info",`Channel opening attempt result:\n${JSON.stringify(logInfo)}`)
return update
}
function parseChannelOptions (product, order) {
if (product.product_type === 'LN_CHANNEL') {
if (order.remote_balance > order.local_balance) {
return false
}
if(order.remote_balance >= order.local_balance){
return false
}
return {
remote_amt: order.remote_balance,
local_amt: order.local_balance
}
}
return false
}
function addPeer ({ order, product }, cb) {
lnWorker('addPeer', {
socket: order.remote_node.addr,
public_key: order.remote_node.public_key
}, (err, data) => {
if (err) {
console.log('Adding peer failed. Could already be connected')
console.log(err)
}
cb(null, data)
})
}
function channelOpener () {
let count = 0
setInterval(() => {
count = 0
}, 60000)
const max = 10
async function openChannel ({ order, product }, cb) {
if (count >= max) {
alert('info', 'Channel opening is being throttled.')
return cb(new Error('Throttled channel opening'))
}
count++
const res = { order }
const op = parseChannelOptions(product, order)
if (!op) return cb(new Error('invalid order options'))
if(op.remote_amt){
op.give_tokens = op.remote_amt
if(op.give_tokens < 0) return cb(new Error('Invalid channel balance amounts'))
op.local_amt = op.local_amt + op.remote_amt
}
const chanOpenConfig = {
local_amt:op.local_amt,
remote_amt: op.remote_amt,
remote_pub_key: order.remote_node.public_key,
is_private: order.private_channel
}
try {
chanOpenConfig.fee_rate = await getOpeningFee()
} catch(err){
console.log("Failed to get chan opening fee")
return cb(err)
}
if(chanOpenConfig.fee_rate >= MAX_CHAN_FEE) return cb(chanErrors.FEE_TOO_HIGH(["FEE IS HIGHER THAN "+MAX_CHAN_FEE]))
console.log(`Opening LN Channel to: ${JSON.stringify(chanOpenConfig,null,2)}`)
lnWorker('openChannel', chanOpenConfig, (err, data) => {
if (err) {
const chanErr = parseChannelOpenErr(err, {
remote_node : order.remote_node
})
res.result = { error: chanErr.toString() }
console.log('Failed to open channel', order._id, chanErr.toString())
return cb(null, res)
}
if (!data.transaction_id) {
console.log('Failed to open channel, no txid:', order._id)
res.result = { error : chanErrors.NO_TX_ID([err,data]) }
return cb(null, res)
}
data.fee_rate = chanOpenConfig.fee_rate
res.result = { channel_tx: data }
cb(null, res)
})
}
return openChannel
}
async function getOpeningFee(cb) {
return new Promise((accept, reject) =>{
callWorker('svc:btc:mempool', 'getCurrrentFeeThreshold', [{}], (err,data)=>{
if(err) return reject(err)
accept(data.min_fee)
})
})
}
function alert (level, msg) {
gClient.send('svc:monitor:slack', [level, 'ln_channel', msg], () => {})
}
const gClient = new GrenacheClient()
async function main (cb) {
const orders = await getPaidOrders()
if (orders.length === 0) {
console.log(`No orders to process. ${Date.now()}`)
return cb()
}
const openChannel = channelOpener()
const products = await getProducts(orders.map(({ product_id }) => product_id))
console.log(`Processing ${orders.length} for ${products.length} Products`)
async.mapSeries(orders, (order, next) => {
const product = find(products, ({ _id }) => order.product_id.equals(_id))
if (!product) return next(new Error('Failed to find product'))
addPeer({ product, order }, () => {
openChannel({ product, order }, next)
})
}, async (err, data) => {
if (err) {
console.log('Error processing orders', err)
return cb(err)
}
try {
await updateOrders(data)
} catch (err) {
console.log('Failed to update orders', err)
}
cb()
})
}
let running = false
setInterval(() => {
if (running) {
console.log('Channel opener is already running.')
return
}
running = true
try {
main(() => {
running = false
})
} catch (err) {
console.log('Channel opener failed')
console.log(err)
running = false
}
}, 5000)