-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
232 lines (183 loc) · 5.87 KB
/
index.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
const invoices = require('invoices')
const Lnd = require('./lnd')
const CLightning = require('./c-lightning')
const metadata = require('./metadata')
const { EventEmitter } = require('events')
const MAX_SUBSCRIBER_CACHE = 500
module.exports = class Payment extends EventEmitter {
constructor (dazaar, payment, opts = {}) {
super()
this.dazaar = dazaar
this.payment = backwardsCompat(payment)
dazaar.on('peer-add', () => {
if (++this._peerCount !== 1) return
for (const req of this._requests) {
if (req.flushed) continue
req.flushed = true
dazaar.broadcast('lnd-pay-request', { amount: req.amount })
}
})
dazaar.on('peer-remove', () => this._peerCount--)
this.destroyed = false
this.lightning = node(opts)
this.subscribers = new Map()
this._requests = []
this._peerCount = 0
this.nodeInfo = {}
this.nodeInfo.address = opts.address || null
this.supports = this.constructor.supports
const self = this
this._setupExtensions(function oninvoice (invRaw) {
const inv = invoices.parsePaymentRequest(invRaw)
for (let i = 0; i < self._requests.length; i++) {
const { amount, description, cb } = self._requests[i]
if (amount === inv.tokens && description === inv.description) {
self._requests.splice(i, 1)
cb(null, invRaw, inv)
return
}
}
if (opts.oninvoice) opts.oninvoice(invRaw, inv)
})
}
initMaybe (cb) {
const self = this
if (this.nodeInfo.id) return cb()
this.lightning.init((err) => {
if (err) return cb(err)
this.lightning.getNodeId(function (err, nodeId) {
if (err) return cb(err)
self.nodeInfo.id = nodeId
cb()
})
})
}
validate (buyerKey, cb) {
if (this.destroyed) return process.nextTick(cb, new Error('Seller is shutting down'))
this.lightning.init((err) => {
if (err) return cb(err)
const tail = this._get(buyerKey)
const timeout = setTimeout(ontimeout, 20000)
let timedout = false
if (tail.synced || tail.active()) return process.nextTick(onsynced)
tail.on('synced', onsynced)
tail.on('update', onupdate)
function ontimeout () {
timedout = true
onsynced()
}
function onupdate () {
if (tail.active()) onsynced()
}
function onsynced () {
tail.removeListener('synced', onsynced)
tail.removeListener('update', onupdate)
clearTimeout(timeout)
const time = tail.remainingTime()
if (time <= 0) return cb(new Error('No time left on subscription' + (timedout ? 'after timeout' : '')))
cb(null, {
type: 'time',
remaining: time
})
}
})
}
sell (request, buyerKey, cb) {
if (this.lightning === null) return cb(new Error('No lightning node connected, only buy permitted.'))
if (!cb) cb = noop
this.lightning.init((err) => {
if (err) return cb(err)
this.lightning.addInvoice(this._filter(buyerKey), request.amount, cb)
})
}
requestInvoice (amount, cb) {
this.dazaar.ready((err) => {
if (err) return cb(err)
if (this.destroyed) return cb(new Error('Destroyed'))
this._requests.push({
amount,
flushed: this._peerCount > 0,
description: 'dazaar: ' + this.dazaar.seller.toString('hex') + ' ' + this.dazaar.key.toString('hex'),
cb
})
this.dazaar.broadcast('lnd-pay-request', { amount })
})
}
buy (seller, amount, auth, cb) {
if (typeof seller === 'number') return this.buy(null, seller, amount, auth)
if (typeof auth === 'function') return this.buy(null, amount, null, auth)
this.requestInvoice(amount, (err, req) => {
if (err) return cb(err)
this.lightning.init((err) => {
if (err) return cb(err)
this.lightning.payInvoice(req, cb)
})
})
}
destroy () {
if (this.destroyed) return
this.destroyed = true
for (const tail of this.subscribers.values()) {
tail.destroy()
}
this.lightning.destroy()
const requests = this._requests
this._requests = []
for (const { cb } of requests) {
cb(new Error('Destroyed'))
}
}
_filter (key, seller = true) {
return seller ? metadata(this.dazaar.key, key) : metadata(key, this.dazaar.key)
}
_get (buyer) {
const h = buyer.toString('hex')
if (this.subscribers.has(h)) return this.subscribers.get(h)
if (this.subscribers.size >= MAX_SUBSCRIBER_CACHE) this._gc()
const tail = this.lightning.subscription(this._filter(buyer), this.payment)
this.subscribers.set(h, tail)
return tail
}
_gc () {
for (const [h, tail] of this.subscribers) {
tail.destroy()
this.subscribers.delete(h)
return
}
}
_setupExtensions (oninvoice) {
const self = this
this.dazaar.receive('lnd-pay-request', function (request, stream) {
self.sell(request, stream.remotePublicKey, function (err, invoice) {
if (err) self.emit('error', err)
self.dazaar.send('lnd-invoice', invoice, stream)
})
})
this.dazaar.receive('lnd-invoice', oninvoice)
}
static supports (p) {
p = backwardsCompat(p)
const supported = ['BTC', 'SATS']
return !!p.currency && (p.method.toLowerCase() === 'lightning' && supported.includes(p.currency.toUpperCase()))
}
}
function node (opts) {
if (opts.implementation === 'lnd') return new Lnd(opts)
if (opts.implementation === 'c-lightning') return new CLightning(opts)
return null
}
function noop () {}
function backwardsCompat (payment) {
if (!payment) return payment
if (payment.currency === 'LightningSats') {
payment = { ...payment }
payment.method = 'Lightning'
payment.currency = 'SATS'
}
if (payment.currency === 'LightningBTC') {
payment = { ...payment }
payment.method = 'Lightning'
payment.currency = 'BTC'
}
return payment
}