-
-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathlnd.go
388 lines (311 loc) · 8.89 KB
/
lnd.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
package lightning
import (
"context"
"crypto/x509"
"encoding/hex"
"github.com/go-errors/errors"
"github.com/lightningnetwork/lnd/lnrpc"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
"google.golang.org/grpc/metadata"
"google.golang.org/grpc/status"
"io"
"sync"
"time"
)
var (
beginCertificateBlock = []byte("-----BEGIN CERTIFICATE-----\n")
endCertificateBlock = []byte("\n-----END CERTIFICATE-----")
)
type nextClient struct {
sync.Mutex
id uint32
}
type LndNodeConfig struct {
Uri string
CertBytes []byte
MacaroonBytes []byte
Logger Logger
}
type LndNode struct {
uri string
tlsCredentials credentials.TransportCredentials
macaroonMetadata metadata.MD
conn *grpc.ClientConn
client lnrpc.LightningClient
unlocker lnrpc.WalletUnlockerClient
logger Logger
invoicesClients map[uint32]*InvoicesClient
nextInvoicesClient nextClient
statusClients map[uint32]*StatusClient
nextStatusClient nextClient
locked bool
status Status
}
// Compile time check for protocol compatibility
var _ Node = (*LndNode)(nil)
func NewLndNode(config *LndNodeConfig) (*LndNode, error) {
node := &LndNode{
logger: config.Logger,
invoicesClients: make(map[uint32]*InvoicesClient),
statusClients: make(map[uint32]*StatusClient),
status: StatusStopped,
}
if config.Uri != "" {
node.setUri(config.Uri)
}
if config.CertBytes != nil {
err := node.setTlsCredentials(config.CertBytes, false)
if err != nil {
return nil, errors.Errorf("unable to set certificate: %v", err)
}
}
if config.MacaroonBytes != nil {
node.setMacaroon(config.MacaroonBytes)
}
return node, nil
}
func (r *LndNode) setUri(uri string) {
r.uri = uri
}
func (r *LndNode) setTlsCredentials(certBytes []byte, wrapped bool) error {
cert := x509.NewCertPool()
fullCertBytes := certBytes
if !wrapped {
fullCertBytes = append(beginCertificateBlock, fullCertBytes...)
fullCertBytes = append(fullCertBytes, endCertificateBlock...)
}
if ok := cert.AppendCertsFromPEM(fullCertBytes); !ok {
return errors.Errorf("unable to append")
}
r.tlsCredentials = credentials.NewClientTLSFromCert(cert, "")
return nil
}
func (r *LndNode) setMacaroon(macaroonBytes []byte) {
hexMacaroon := hex.EncodeToString(macaroonBytes)
r.macaroonMetadata = metadata.Pairs("macaroon", hexMacaroon)
}
func (r *LndNode) Start() error {
var err error
r.logger.Infof("starting %s", r.uri)
r.conn, err = grpc.Dial(r.uri, grpc.WithTransportCredentials(r.tlsCredentials))
if err != nil {
return errors.Errorf("Could not connect to lightning node: %v", err)
}
r.client = lnrpc.NewLightningClient(r.conn)
r.unlocker = lnrpc.NewWalletUnlockerClient(r.conn)
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, r.macaroonMetadata)
info, err := r.client.GetInfo(ctx, &lnrpc.GetInfoRequest{})
if err != nil {
// try to unlock to find out whether there's an existing wallet
_, err = r.unlocker.UnlockWallet(ctx, &lnrpc.UnlockWalletRequest{WalletPassword: []byte{}})
if status, ok := status.FromError(err); err != nil && ok {
if status.Message() == "wallet not found" {
r.updateStatus(StatusUninitialized)
return nil
}
}
r.updateStatus(StatusLocked)
return nil
}
if info.SyncedToChain {
r.updateStatus(StatusStarted)
} else {
r.updateStatus(StatusStarted)
}
go r.run()
return nil
}
func (r *LndNode) run() {
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, r.macaroonMetadata)
invoices, err := r.client.SubscribeInvoices(ctx, &lnrpc.InvoiceSubscription{})
if err != nil {
r.logger.Errorf("Could not subscribe to invoices: %v", err)
return
}
for {
invoice, err := invoices.Recv()
if err == io.EOF {
r.logger.Errorf("Got EOF from invoices stream: %v", err)
time.Sleep(1 * time.Second)
continue
}
if err != nil {
errStatus, ok := status.FromError(err)
if !ok {
r.logger.Errorf("Could not get status from err: %v", err)
}
if errStatus.Code() == 1 {
r.logger.Infof("Stopping invoice listener")
break
} else if err != nil {
r.logger.Errorf("Failed receiving subscription items: %v", err)
break
}
}
for _, client := range r.invoicesClients {
client.Invoices <- &Invoice{
RHash: hex.EncodeToString(invoice.RHash),
PaymentRequest: invoice.PaymentRequest,
MSat: invoice.Value,
Settled: invoice.Settled,
Memo: invoice.Memo,
}
}
}
}
func (r *LndNode) Stop() error {
r.updateStatus(StatusStopped)
if r.conn != nil {
err := r.conn.Close()
if err != nil {
return errors.Errorf("Could not close connection: %v", err)
}
}
r.closeAllInvoiceSubscriptions()
return nil
}
func (r *LndNode) GetInvoice(rHash string) (*Invoice, error) {
if r.client == nil {
return nil, errors.Errorf("Node not started")
}
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, r.macaroonMetadata)
res, err := r.client.LookupInvoice(ctx, &lnrpc.PaymentHash{
RHashStr: rHash,
})
if err != nil {
return nil, errors.Errorf("Could not find invoice: %v", err)
}
return &Invoice{
Settled: res.Settled,
RHash: hex.EncodeToString(res.RHash),
PaymentRequest: res.PaymentRequest,
Memo: res.Memo,
MSat: res.Value,
}, nil
}
func (r *LndNode) AddInvoice(req *InvoiceRequest) (*Invoice, error) {
if r.client == nil {
return nil, errors.Errorf("Node not started")
}
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, r.macaroonMetadata)
res, err := r.client.AddInvoice(ctx, &lnrpc.Invoice{
Memo: "Candy for 8 satoshis",
Value: 8,
})
if err != nil {
return nil, errors.Errorf("Could not add invoice: %v", err)
}
return &Invoice{
Settled: false,
RHash: hex.EncodeToString(res.RHash),
PaymentRequest: res.PaymentRequest,
Memo: req.Memo,
MSat: req.MSat,
}, nil
}
func (r *LndNode) SubscribeInvoices() (*InvoicesClient, error) {
client := &InvoicesClient{
Invoices: make(chan *Invoice),
cancelChan: make(chan struct{}),
node: r,
}
r.nextInvoicesClient.Lock()
client.Id = r.nextInvoicesClient.id
r.nextInvoicesClient.id++
r.nextInvoicesClient.Unlock()
r.invoicesClients[client.Id] = client
return client, nil
}
func (r *LndNode) closeAllInvoiceSubscriptions() {
for _, client := range r.invoicesClients {
client.Cancel()
}
}
func (r *LndNode) unsubscribeInvoices(client *InvoicesClient) {
delete(r.invoicesClients, client.Id)
close(client.cancelChan)
}
func (r *LndNode) GenerateSeed() ([]string, error) {
client := lnrpc.NewWalletUnlockerClient(r.conn)
res, err := client.GenSeed(context.Background(), &lnrpc.GenSeedRequest{})
if status, ok := status.FromError(err); err != nil && ok {
if status.Message() == "wallet already exists" {
return nil, errors.New("wallet already exists")
}
return nil, errors.New(status.Message())
}
return res.CipherSeedMnemonic, nil
}
func (r *LndNode) Init(password string, mnemonic []string) error {
client := lnrpc.NewWalletUnlockerClient(r.conn)
_, err := client.InitWallet(context.Background(), &lnrpc.InitWalletRequest{
WalletPassword: []byte(password),
CipherSeedMnemonic: mnemonic,
})
if status, ok := status.FromError(err); err != nil && ok {
if status.Message() == "wallet already exists" {
return errors.New("wallet already exists")
}
return errors.New(status.Message())
}
r.updateStatus(StatusStarted)
return nil
}
func (r *LndNode) Unlock(password string) error {
client := lnrpc.NewWalletUnlockerClient(r.conn)
_, err := client.UnlockWallet(context.Background(), &lnrpc.UnlockWalletRequest{
WalletPassword: []byte(password),
})
if err != nil {
return errors.Errorf("unable to unlock: %v", err)
}
r.updateStatus(StatusStarted)
return nil
}
func (r *LndNode) Restore() error {
if r.client == nil {
return errors.Errorf("Node not started")
}
ctx := context.Background()
ctx = metadata.NewOutgoingContext(ctx, r.macaroonMetadata)
_, err := r.client.RestoreChannelBackups(ctx, &lnrpc.RestoreChanBackupRequest{
Backup: &lnrpc.RestoreChanBackupRequest_MultiChanBackup{
MultiChanBackup: []byte{},
},
})
if err != nil {
return errors.Errorf("Could not restore channels: %v", err)
}
return nil
}
func (r *LndNode) updateStatus(status Status) {
r.status = status
for _, client := range r.statusClients {
client.Status <- status
}
}
func (r *LndNode) Status() Status {
return r.status
}
func (r *LndNode) SubscribeStatus() *StatusClient {
client := &StatusClient{
Status: make(chan Status),
cancelChan: make(chan struct{}),
node: r,
}
r.nextStatusClient.Lock()
client.Id = r.nextStatusClient.id
r.nextStatusClient.id++
r.nextStatusClient.Unlock()
r.statusClients[client.Id] = client
return client
}
func (r *LndNode) unsubscribeStatus(client *StatusClient) {
delete(r.statusClients, client.Id)
close(client.cancelChan)
}