forked from bitfinexcom/dazaar-payment-lightning
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathc-lightning.js
199 lines (155 loc) · 4.71 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
const crypto = require('crypto')
const path = require('path')
const unixson = require('unixson')
const clerk = require('payment-tracker')
const { EventEmitter } = require('events')
module.exports = class Payment {
constructor (opts) {
this.client = unixson(path.join(opts.lightningdDir, opts.network) + '/lightning-rpc')
this.requests = []
}
init (cb) {
cb()
}
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))
}
destroy () {
this.requests = []
}
subscription (filter, paymentInfo) {
const self = this
let perSecond = 0
if (typeof paymentInfo === 'object' && paymentInfo) { // dazaar card
perSecond = convertDazaarPayment(paymentInfo)
} else {
try {
const match = paymentInfo.trim().match(/^(\d(?:\.\d+)?)\s*BTC\s*\/\s*s$/i)
if (!match) throw new Error()
perSecond = Number(match[1]) * 10 ** 8
} catch {
const match = paymentInfo.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 account = clerk(perSecond, paymentInfo.minSeconds, paymentInfo.paymentDelay)
sub.synced = false
sync(tail)
sub.active = account.active
sub.remainingTime = account.remainingTime
sub.remainingFunds = account.remainingFunds
sub.destroy = function () {
sub.removeListener('data', filterInvoice)
}
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.forEach(payment =>
account.add({
amount: payment.msatoshi / 1000,
time: parseInt(payment.paid_at) * 1000
}))
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 => {
if (res.error) throw new Error(res.error.message)
const invoice = {
request: res.result.bolt11,
amount: amount
}
cb(null, invoice)
})
.catch(err => cb(err))
}
payInvoice (paymentRequest, cb) {
if (!cb) cb = noop
self.client.pay(paymentRequest)
.then(payment => {
if (payment.error) return cb(new Error(payment.error.message))
cb(null, payment)
})
.catch(err => cb(err))
}
}
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.toUpperCase() === 'SATS') satoshiAmt = Number(pay.amount)
if (pay.currency.toUpperCase() === 'BTC') satoshiAmt = toSats(Number(pay.amount))
const perSecond = satoshiAmt / (Number(pay.interval) * ratio)
if (!perSecond) throw new Error('Invalid payment info')
return perSecond
}