-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathc-lightning.js
244 lines (187 loc) · 5.88 KB
/
c-lightning.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
const crypto = require('crypto')
const unixson = require('unixson')
const { EventEmitter } = require('events')
module.exports = class Payment {
constructor (opts) {
this.client = unixson(opts.lightningdDir + '/regtest/lightning-rpc')
this.requests = []
}
getNodeId (cb) {
this.client.getinfo()
.then(res => {
cb(null, res.result.id)
})
.catch(err => cb(err))
}
connect (opts, cb) {
if (!cb) cb = noop
const self = this
this.client.listpeers()
.then(res => {
const peers = res.result.peers
if (peers.indexOf(peer => peer.pub_key === opts.id) >= 0) return cb()
const [host, port] = opts.address.split(':')
self.client.connect(opts.pubkey, host, port)
.then(res => cb(null, res))
.catch(err => cb(err))
})
.catch(err => cb(err))
}
subscription (filter, rate) {
const self = this
let perSecond = 0
if (typeof rate === 'object' && rate) { // dazaar card
perSecond = convertDazaarPayment(rate)
} else {
try {
const match = rate.trim().match(/^(\d(?:\.\d+)?)\s*BTC\s*\/\s*s$/i)
if (!match) throw new Error()
perSecond = Number(match[1]) * 10 ** 8
} catch {
const match = rate.trim().match(/^(\d+)(?:\.\d+)?\s*Sat\/\s*s$/i)
if (!match) throw new Error('rate should have the form "n....nn Sat/s" or "n...nn BTC/s"')
perSecond = Number(match[1])
}
}
const sub = new EventEmitter()
let activePayments = []
sub.synced = false
sync(tail)
sub.active = function (minSeconds) {
return sub.remainingFunds(minSeconds) > 0
}
sub.destroy = function () {}
sub.remainingTime = function (minSeconds) {
const funds = sub.remainingFunds(minSeconds)
return Math.floor(Math.max(0, funds / perSecond * 1000))
}
sub.remainingFunds = function (minSeconds) {
if (!minSeconds) minSeconds = 0
const now = Date.now() + minSeconds * 1000
const funds = activePayments.reduce(leftoverFunds, 0)
return funds
function leftoverFunds (funds, payment, i) {
const nextTime = i + 1 < activePayments.length ? activePayments[i + 1].time : now
const consumed = perSecond * (nextTime - payment.time) / 1000
funds += payment.amount - consumed
return funds > 0 ? funds : 0
}
}
return sub
function sync (cb) {
self.client.listinvoices()
.then(res => {
const dazaarPayments = res.result.invoices
.filter(invoice => invoice.status === 'paid' && invoice.description === filter)
sub._lastpayIndex = Math.max(...dazaarPayments.map(inv => inv.pay_index))
const payments = dazaarPayments.map(payment => ({
amount: payment.msatoshi / 1000,
time: parseInt(payment.paid_at) * 1000
}))
activePayments = [].concat(activePayments, payments)
sub.synced = true
sub.emit('synced')
cb()
})
.catch(err => {
sub.emit('warning', err)
})
}
function tail (index) {
index = index || sub._lastpayIndex
self.client.waitanyinvoice(index)
.then(function (res) {
const invoice = res.result
filterInvoice(invoice)
return tail(++index)
})
.catch(err => {
sub.emit('warning', err)
})
}
function filterInvoice (invoice) {
if (invoice.description !== filter) return
const amount = parseInt(invoice.msatoshi) / 1000
const time = parseInt(invoice.paid_at) * 1000
activePayments.push({ amount, time })
sub.emit('update')
}
}
addInvoice (filter, amount, cb) {
// generate unique label per invoice
const tag = `${filter}:${Date.now()}`
const label = crypto.createHash('sha256')
.update(Buffer.from(tag))
.digest('base64')
const amountMsat = amount * 1000
return this.client.invoice(amountMsat, label, filter)
.then(res => {
const invoice = {
request: res.result.bolt11,
amount: amount
}
cb(null, invoice)
})
.catch(err => cb(err))
}
payInvoice (paymentRequest, cb) {
const self = this
if (!cb) cb = noop
self.client.decodepay(paymentRequest)
.then(res => {
const details = res.result
const [label, info] = details.description.split(':')
if (label !== 'dazaar') return fail()
const [seller, buyer] = info.trim().split(' ')
const invoice = {
buyer,
seller,
amount: parseInt(details.msatoshi) / 1000
}
const index = self.requests.findIndex(matchRequest(invoice))
if (index === -1) return fail()
self.requests.splice(index, 1)
self.client.pay(paymentRequest)
.then(payment => {
if (payment.error) return cb(new Error(payment.error.message))
cb(null, payment)
})
.catch(err => cb(err))
})
.catch(err => cb(err))
function fail () {
return cb(new Error('unrecognised invoice'))
}
function matchRequest (inv) {
return req => {
return req.buyer === inv.buyer &&
req.seller === inv.seller &&
req.amount === inv.amount
}
}
}
}
function noop () {}
function toSats (btcAmount) {
return btcAmount * 10 ** 8
}
function convertDazaarPayment (pay) {
let ratio = 0
switch (pay.unit) {
case 'minutes':
ratio = 60
break
case 'seconds':
ratio = 1
break
case 'hours':
ratio = 3600
break
}
let satoshiAmt
if (pay.currency === 'LightningSats') satoshiAmt = Number(pay.amount)
if (pay.currency === 'LightningBTC') satoshiAmt = toSats(Number(pay.amount))
const perSecond = satoshiAmt / (Number(pay.interval) * ratio)
if (!perSecond) throw new Error('Invalid payment info')
return perSecond
}