-
Notifications
You must be signed in to change notification settings - Fork 1
/
lightning.go
534 lines (445 loc) · 14.2 KB
/
lightning.go
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
package lightning
import (
"encoding/json"
"errors"
"sync"
"github.com/imperviousai/imp-daemon/comm"
"github.com/imperviousai/imp-daemon/lightning/node"
"go.uber.org/zap"
)
//go:generate mockgen --destination=./mock/lightning_manager_mock.go --package=mock github.com/imperviousai/imp-daemon/lightning LightningManager
// LightningManager is the manager in charge of subscribing to and
// managing multiple lightning nodes. Data transfer happens via channels
// in order to abstract base functionality.
type LightningManager interface {
// Status will report the status of the Lightning Nodes connected
Status() ([]NodeStatus, error)
// Subscribe will subscribe to keysend events on all nodes on configured chan.
Subscribe() error
// CheckMsg will check the message to see if it can send down this transport
CheckMsg(endpoint string, msg *comm.DIDCommMsg) bool
// SendData will send a keysend message from a specific node public key.
SendData(endpoint string, msg *comm.DIDCommMsg) error
// AddNode will add a node to the LightningManager.
// If subscriptions are active, will start on new node.
AddNode(node.Node) error
// SignMessage will sign the provided message using a node
SignMessage([]byte) ([]byte, error)
// VerifySignature will verify the provided signature using a node
VerifySignature([]byte, []byte) (bool, error)
// GenerateInvoice will generate an invoice from one of the active nodes.
GenerateInvoice(int64, string) (string, error)
// PayInvoice will pay an invoice from one of the active nodes.
PayInvoice(string) (string, error)
// PayInvoice will check an invoice for payment.
CheckInvoice(string) (bool, error)
// RemoveNode will disconnect & remove node from LightningManager.
RemoveNode(string) error
// Stop will stop the lightning manager and
// all lightning nodes connected to it.
Stop()
// GetChannels Get the channels from the connected LND node
GetChannels() (int64, error)
// ListPayments Get the payments from the connected LND node
ListPayments() (string, error)
// ListInvoices Get the invoices from the connected LND node
ListInvoices() (string, error)
}
type lightningManager struct {
nodeControllers map[string]*nodeController
nodesLock sync.RWMutex
incomingDataChan chan comm.IncomingDIDMessage
subscriptionsActive bool
}
type nodeController struct {
node node.Node
active bool
}
type LightningManagerConfig struct {
IncomingDataChan chan comm.IncomingDIDMessage
}
func NewLightningManager(cfg *LightningManagerConfig) LightningManager {
return &lightningManager{
nodeControllers: make(map[string]*nodeController),
nodesLock: sync.RWMutex{},
incomingDataChan: cfg.IncomingDataChan,
subscriptionsActive: false,
}
}
// Subscribe will subscribe to keysend events on all nodes.
func (l *lightningManager) Subscribe() error {
zap.L().Debug("[LM] Subscribe")
l.nodesLock.RLock()
defer l.nodesLock.RUnlock()
// Allow running without lightning node
if len(l.nodeControllers) == 0 {
return nil
}
for _, nodeCtrl := range l.nodeControllers {
nodeCtrl.active = true
if !nodeCtrl.node.ShouldListen() {
zap.L().Debug("[LM] Subscribe skipping non-listening node")
continue
}
zap.L().Debug("[LM] Subscribe about to subscribe with next node")
if err := nodeCtrl.node.Subscribe(l.incomingDataChan); err != nil {
// ignore the error if just a single node has an issue
// mark the node as inactive
zap.L().Error("[LM] Subcribe failed with node")
nodeCtrl.active = false
continue
}
l.subscriptionsActive = true
zap.L().Debug("[LM] Subcribe succeeded subscription with a node")
}
// if no subscriptions were able to be activated,
// then give warning, this is okay - not every daemon
// wants to listen to a lightning node but can still connect
if !l.subscriptionsActive {
zap.L().Debug("[LM] Not subscribing to any lightning node")
return nil
}
zap.L().Debug("[LM] Subscribe succeeded")
return nil
}
func (l *lightningManager) CheckMsg(endpoint string, msg *comm.DIDCommMsg) bool {
// TODO should maybe try to resolve pubkey or something?
return true
}
// SendData will send a keysend message from a specific node public key.
// If no internal node pubkey was specified then msg will send from any.
func (l *lightningManager) SendData(toPubkey string, msgData *comm.DIDCommMsg) error {
zap.L().Debug("[LM] SendData",
zap.String("to_pubkey", toPubkey),
// zap.Any("message", msgData),
zap.Int64("amount", msgData.GetAmountMetadata()),
)
// Check amount, can't send for free
amt := msgData.GetAmountMetadata()
if amt == 0 {
return errors.New("Cannot send 0 amount payment")
}
l.nodesLock.RLock()
defer l.nodesLock.RUnlock()
if len(l.nodeControllers) < 1 {
zap.L().Error("[LM] SendData had no nodes available to send from")
return errors.New("No nodes available to send from")
}
// If no node is specified, try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
msgBytes, err := json.Marshal(msgData)
if err != nil {
return err
}
if err := nodeCtrl.node.Keysend(toPubkey, msgBytes, amt); err != nil {
zap.L().Error("[LM] SendData failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// Keysend complete, return
zap.L().Debug("[LM] SendData successful")
return nil
}
// If it went through all nodes without success, return last error
zap.L().Error("[LM] SendData failed", zap.String("error", lastErr.Error()))
return lastErr
}
func (l *lightningManager) SignMessage(msg []byte) ([]byte, error) {
zap.L().Debug("[LM] SignMessage",
zap.ByteString("message", msg),
)
// TODO specify from pubkey
// If no node is specified, try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
signature, err := nodeCtrl.node.SignMessage(msg)
if err != nil {
zap.L().Error("[LM] SignMessage failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// sign message complete, return
zap.L().Debug("[LM] SignMessage successful")
return signature, nil
}
zap.L().Error("[LM] SignMessage failed", zap.String("error", lastErr.Error()))
return nil, lastErr
}
func (l *lightningManager) VerifySignature(msg []byte, signature []byte) (bool, error) {
zap.L().Debug("[LM] VerifySignature",
zap.ByteString("message", msg),
zap.ByteString("signature", msg),
)
// Try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.VerifySignature(msg, signature)
if err != nil {
zap.L().Error("[LM] VerifySignature failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// result acquired, return
zap.L().Debug("[LM] VerifySignature successful")
return result, nil
}
zap.L().Error("[LM] VerifySignature failed", zap.String("error", lastErr.Error()))
return false, lastErr
}
func (l *lightningManager) GenerateInvoice(amt int64, memo string) (string, error) {
zap.L().Debug("[LM] GenerateInvoice",
zap.Int64("amount", amt),
zap.String("memo", memo),
)
// Try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.GenerateInvoice(amt, memo)
if err != nil {
zap.L().Error("[LM] GenerateInvoice failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// result acquired, return
zap.L().Debug("[LM] GenerateInvoice successful")
return result, nil
}
zap.L().Error("[LM] GenerateInvoice failed", zap.String("error", lastErr.Error()))
return "", lastErr
}
func (l *lightningManager) PayInvoice(inv string) (string, error) {
zap.L().Debug("[LM] PayInvoice",
zap.String("invoice", inv),
)
// Try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.PayInvoice(inv)
if err != nil {
zap.L().Error("[LM] PayInvoice failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// result acquired, return
zap.L().Debug("[LM] PayInvoice successful")
return result, nil
}
zap.L().Error("[LM] PayInvoice failed", zap.String("error", lastErr.Error()))
return "", lastErr
}
func (l *lightningManager) CheckInvoice(inv string) (bool, error) {
zap.L().Debug("[LM] CheckInvoice",
zap.String("invoice", inv),
)
// Try all active ones
var lastErr error
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.CheckInvoice(inv)
if err != nil {
zap.L().Error("[LM] CheckInvoice failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
// result acquired, return
zap.L().Debug("[LM] CheckInvoice successful")
return result, nil
}
zap.L().Error("[LM] CheckInvoice failed", zap.String("error", lastErr.Error()))
return false, lastErr
}
// AddNode will add a node to the LightningManager.
// If subscriptions are active, will start on new node.
func (l *lightningManager) AddNode(node node.Node) error {
zap.L().Debug("[LM] AddNode")
l.nodesLock.Lock()
defer l.nodesLock.Unlock()
nodePubKey := node.GetPubkey()
// If already subscribed, start subscription for this node.
isActive := false
if l.subscriptionsActive {
isActive = true
if node.ShouldListen() {
err := node.Subscribe(l.incomingDataChan)
if err != nil {
zap.L().Error("[LM] AddNode failed subscribing to added node", zap.String("error", err.Error()))
return err
}
}
}
l.nodeControllers[nodePubKey] = &nodeController{
node: node,
active: isActive,
}
zap.L().Debug("[LM] AddNode succeeded")
return nil
}
// RemoveNode will disconnect & remove node from LightningManager.
func (l *lightningManager) RemoveNode(id string) error {
zap.L().Debug("[LM] RemoveNode")
l.nodesLock.Lock()
defer l.nodesLock.Unlock()
if nodeCtrl, ok := l.nodeControllers[id]; ok {
if err := nodeCtrl.node.Disconnect(); err != nil {
zap.L().Error("[LM] RemoveNode failed", zap.String("error", err.Error()))
return err
}
delete(l.nodeControllers, id)
zap.L().Debug("[LM] RemoveNode succeeded")
return nil
}
zap.L().Error("[LM] RemoveNode node does not exist")
return errors.New("Node does not exist")
}
// Stop will stop the lightning manager and
// all lightning nodes connected to it.
func (l *lightningManager) Stop() {
zap.L().Debug("[LM] Stop")
l.nodesLock.Lock()
defer l.nodesLock.Unlock()
var nodeWg sync.WaitGroup
// Only go through active nodes.
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
nodeWg.Add(1)
go func(n node.Node, wg *sync.WaitGroup) {
zap.L().Debug("[LM] Stop requested for node")
if err := n.Disconnect(); err != nil {
zap.L().Error("[LM] Stop failed", zap.String("error", err.Error()))
}
zap.L().Debug("[LM] Stoped node")
nodeWg.Done()
}(nodeCtrl.node, &nodeWg)
}
zap.L().Debug("[LM] Waiting for all nodes to stop")
nodeWg.Wait()
zap.L().Debug("[LM] Stop successful")
}
type NodeStatus struct {
Pubkey string
Active bool
}
func (l *lightningManager) Status() ([]NodeStatus, error) {
zap.L().Debug("[LM] Status")
l.nodesLock.Lock()
defer l.nodesLock.Unlock()
nodeStatuses := make([]NodeStatus, 0, len(l.nodeControllers))
// Go through each node
for _, nodeCtrl := range l.nodeControllers {
active := nodeCtrl.active
// Double check if active nodes are indeed connected
if active {
_, err := nodeCtrl.node.GetInfo()
if err != nil {
zap.L().Error("[LM] Node status check failed",
zap.String("pubkey", nodeCtrl.node.GetPubkey()),
zap.String("error", err.Error()),
)
active = false
}
}
nodeStatuses = append(nodeStatuses, NodeStatus{
Pubkey: nodeCtrl.node.GetPubkey(),
Active: active,
})
}
return nodeStatuses, nil
}
// GetChannels Get the channels from the connected LND node
func (l *lightningManager) GetChannels() (int64, error) {
zap.L().Debug("[LM] GetChannels Called")
// Try all active ones
var lastErr error
var total int64 = 0
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.GetChannels()
if err != nil {
zap.L().Error("[LM] Getchannels failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
total += result
// result acquired, return
return total, nil
}
zap.L().Error("[LM] Getchannels failed", zap.String("error", lastErr.Error()))
return 0, lastErr
}
// ListPayments Get the transactions from the connected LND node
func (l *lightningManager) ListPayments() (string, error) {
zap.L().Debug("[LM] ListPayments Called")
// Try all active ones
var lastErr error
var resp string
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.ListPayments()
if err != nil {
zap.L().Error("[LM] ListPayments failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
resp += result
// result acquired, return
return resp, nil
}
zap.L().Error("[LM] ListPayments failed", zap.String("error", lastErr.Error()))
return "", lastErr
}
// ListInvoices Get the invoices from the connected LND node
func (l *lightningManager) ListInvoices() (string, error) {
zap.L().Debug("[LM] ListInvoices Called")
// Try all active ones
var lastErr error
var resp string
for _, nodeCtrl := range l.nodeControllers {
if !nodeCtrl.active {
continue
}
result, err := nodeCtrl.node.ListInvoices()
if err != nil {
zap.L().Error("[LM] ListInvoices failed through node, trying next..", zap.String("error", err.Error()))
// Try the next node if error
lastErr = err
continue
}
resp += result
// result acquired, return
return resp, nil
}
zap.L().Error("[LM] ListInvoices failed", zap.String("error", lastErr.Error()))
return "", lastErr
}