-
Notifications
You must be signed in to change notification settings - Fork 2
/
lnd.go
424 lines (363 loc) · 10.9 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
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
package lightning
import (
"context"
"encoding/hex"
"errors"
"fmt"
"strconv"
"strings"
"time"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/lndclient"
"github.com/lightningnetwork/lnd/lnrpc"
"github.com/lightningnetwork/lnd/lnrpc/invoicesrpc"
"github.com/lightningnetwork/lnd/lnrpc/routerrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/routing/route"
"github.com/lightningnetwork/lnd/zpay32"
)
//go:generate moq -stub -skip-ensure -out lnd_mock_test.go . channeler router invoicer
// channeler is the minimum channel requirements from LND.
type channeler interface {
DescribeGraph(ctx context.Context, includeUnannounced bool) (*lndclient.Graph, error)
ForwardingHistory(ctx context.Context,
req lndclient.ForwardingHistoryRequest) (*lndclient.ForwardingHistoryResponse, error)
GetChanInfo(ctx context.Context, chanId uint64) (*lndclient.ChannelEdge, error)
GetInfo(ctx context.Context) (*lndclient.Info, error)
GetNodeInfo(ctx context.Context, pubkey route.Vertex,
includeChannels bool) (*lndclient.NodeInfo, error)
ListChannels(ctx context.Context, activeOnly, publicOnly bool) ([]lndclient.ChannelInfo, error)
UpdateChanPolicy(ctx context.Context, req lndclient.PolicyUpdateRequest, chanPoint *wire.OutPoint) error
}
// router is the minimum routing requirements from LND.
type router interface {
SendPayment(ctx context.Context, request lndclient.SendPaymentRequest) (chan lndclient.PaymentStatus, chan error, error)
SubscribeHtlcEvents(ctx context.Context) (<-chan *routerrpc.HtlcEvent, <-chan error, error)
}
// invoicer is the minimum routing requirements from LND.
type invoicer interface {
AddInvoice(ctx context.Context, in *invoicesrpc.AddInvoiceData) (lntypes.Hash, string, error)
}
// NewLndClient backed by a single LND lightning node.
func NewLndClient(s *lndclient.GrpcLndServices, network string) LndClient {
return LndClient{
c: s.Client,
i: s.Client,
r: s.Router,
network: network,
}
}
// LndClient client backed by LND node.
type LndClient struct {
c channeler
r router
i invoicer
network string
}
// GetInfo of local node.
func (l LndClient) GetInfo(ctx context.Context) (*Info, error) {
i, err := l.c.GetInfo(ctx)
if err != nil {
return &Info{}, err
}
info := Info{
PubKey: PubKey(hex.EncodeToString(i.IdentityPubkey[:])),
}
return &info, nil
}
// DescribeGraph of the Lightning Network.
func (l LndClient) DescribeGraph(ctx context.Context) (*Graph, error) {
g, err := l.c.DescribeGraph(ctx, false)
if err != nil {
return &Graph{}, err
}
// marshall nodes
nodes := make([]Node, len(g.Nodes))
for i, n := range g.Nodes {
nodes[i] = Node{
PubKey: PubKey(n.PubKey.String()),
Alias: n.Alias,
Updated: n.LastUpdate,
Addresses: n.Addresses,
}
}
// marshall edges
edges := make([]Edge, len(g.Edges))
for i, e := range g.Edges {
edges[i] = Edge{
Capacity: Satoshi(e.Capacity.ToUnit(btcutil.AmountSatoshi)),
Node1: PubKey(e.Node1.String()),
Node2: PubKey(e.Node2.String()),
}
}
graph := &Graph{
Nodes: nodes,
Edges: edges,
}
return graph, nil
}
func getRemotePubkey(local *lndclient.Info, edge *lndclient.ChannelEdge) route.Vertex {
remotePubkey := edge.Node1
if local.IdentityPubkey == remotePubkey {
remotePubkey = edge.Node2
}
return remotePubkey
}
func getRemoteFeePPM(local *lndclient.Info, edge *lndclient.ChannelEdge) (FeePPM, error) {
if edge.Node1Policy == nil || edge.Node2Policy == nil {
return 0, fmt.Errorf("channel node policy is missing in channel edge: %v", edge)
}
localFee := FeePPM(edge.Node2Policy.FeeRateMilliMsat)
if local.IdentityPubkey == edge.Node1 {
localFee = FeePPM(edge.Node1Policy.FeeRateMilliMsat)
}
return localFee, nil
}
// GetChannel with ID.
func (l LndClient) GetChannel(ctx context.Context, channelID ChannelID) (Channel, error) {
// returns a channel edge which doesn't have liquidity info
ce, err := l.c.GetChanInfo(ctx, uint64(channelID))
if err != nil {
return Channel{}, err
}
local, err := l.c.GetInfo(ctx)
if err != nil {
return Channel{}, err
}
remotePubkey := getRemotePubkey(local, ce)
localFee, err := getRemoteFeePPM(local, ce)
if err != nil {
return Channel{}, err
}
remote, err := l.c.GetNodeInfo(ctx, remotePubkey, false)
if err != nil {
return Channel{}, err
}
c := Channel{
Edge: Edge{
Capacity: Satoshi(ce.Capacity.ToUnit(btcutil.AmountSatoshi)),
Node1: PubKey(ce.Node1.String()),
Node2: PubKey(ce.Node2.String()),
},
ChannelID: ChannelID(ce.ChannelID),
LocalFee: localFee,
RemoteNode: Node{
PubKey: PubKey(remote.PubKey.String()),
Alias: remote.Alias,
Updated: remote.LastUpdate,
Addresses: remote.Addresses,
},
}
// get local and remote liquidity from the list channels call
cs, err := l.c.ListChannels(ctx, false, false)
if err != nil {
return Channel{}, err
}
for _, ci := range cs {
if ChannelID(ci.ChannelID) == channelID {
c.LocalBalance = Satoshi(ci.LocalBalance.ToUnit(btcutil.AmountSatoshi))
c.RemoteBalance = Satoshi(ci.RemoteBalance.ToUnit(btcutil.AmountSatoshi))
c.Private = ci.Private
}
}
return c, nil
}
// ListChannels of local node.
func (l LndClient) ListChannels(ctx context.Context) (Channels, error) {
channelInfos, err := l.c.ListChannels(ctx, false, false)
if err != nil {
return nil, err
}
local, err := l.c.GetInfo(ctx)
if err != nil {
return nil, err
}
channels := make([]Channel, len(channelInfos))
for i, ci := range channelInfos {
ce, err := l.c.GetChanInfo(ctx, ci.ChannelID)
if err != nil {
return nil, err
}
remotePubkey := getRemotePubkey(local, ce)
localFee, err := getRemoteFeePPM(local, ce)
if err != nil {
return nil, err
}
remote, err := l.c.GetNodeInfo(ctx, remotePubkey, false)
if err != nil {
return nil, err
}
channels[i] = Channel{
Edge: Edge{
Capacity: Satoshi(ce.Capacity.ToUnit(btcutil.AmountSatoshi)),
Node1: PubKey(ce.Node1.String()),
Node2: PubKey(ce.Node2.String()),
},
ChannelID: ChannelID(ci.ChannelID),
LocalBalance: Satoshi(ci.LocalBalance.ToUnit(btcutil.AmountSatoshi)),
LocalFee: localFee,
RemoteBalance: Satoshi(ci.RemoteBalance.ToUnit(btcutil.AmountSatoshi)),
RemoteNode: Node{
PubKey: PubKey(remote.PubKey.String()),
Alias: remote.Alias,
Updated: remote.LastUpdate,
Addresses: remote.Addresses,
},
Private: ci.Private,
}
}
return channels, nil
}
// SetFees for channel with rate in ppm.
func (l LndClient) SetFees(ctx context.Context, channelID ChannelID, fee FeePPM, maxHTLC MilliSatoshi) error {
ce, err := l.c.GetChanInfo(ctx, uint64(channelID))
if err != nil {
return err
}
outpoint, err := decodeChannelPoint(ce.ChannelPoint)
if err != nil {
return err
}
// opinionated policy
req := lndclient.PolicyUpdateRequest{
BaseFeeMsat: 0,
FeeRate: fee.Rate(),
TimeLockDelta: 80,
MaxHtlcMsat: uint64(maxHTLC),
}
return l.c.UpdateChanPolicy(ctx, req, outpoint)
}
// AddInvoice of amount.
func (l LndClient) AddInvoice(ctx context.Context, amount Satoshi) (Invoice, error) {
in := &invoicesrpc.AddInvoiceData{
Value: lnwire.NewMSatFromSatoshis(btcutil.Amount(amount)),
}
_, invoice, err := l.i.AddInvoice(ctx, in)
return Invoice(invoice), err
}
// SendPayment to pay for invoice.
func (l LndClient) SendPayment(ctx context.Context, invoice Invoice, outChannelID ChannelID, lastHopPubKey PubKey, maxFee FeePPM) (Satoshi, error) {
lhpk, err := route.NewVertexFromStr(string(lastHopPubKey))
if err != nil {
return 0, err
}
// decode invoice to get amount in millisats and calculate max fee from ppm
params, err := lndclient.Network(l.network).ChainParams()
if err != nil {
return 0, err
}
i, err := zpay32.Decode(string(invoice), params)
if err != nil {
return 0, err
}
maxFeeMsat := uint64(float64(*i.MilliSat) * maxFee.Rate())
request := lndclient.SendPaymentRequest{
Invoice: string(invoice),
MaxFeeMsat: lnwire.MilliSatoshi(maxFeeMsat),
OutgoingChanIds: []uint64{uint64(outChannelID)},
LastHopPubkey: &lhpk,
AllowSelfPayment: true,
Timeout: time.Duration(60) * time.Second,
}
status, error, err := l.r.SendPayment(ctx, request)
if err != nil {
return 0, err
}
for {
select {
case s := <-status:
if s.State == lnrpc.Payment_SUCCEEDED {
return Satoshi(s.Fee.ToSatoshis()), nil
}
case e := <-error:
return 0, fmt.Errorf("error paying invoice: %w", e)
}
}
}
// SubscribeChannelUpdates signals when a channel's liquidity changes.
func (l LndClient) SubscribeChannelUpdates(ctx context.Context) (<-chan Channels, <-chan error, error) {
cc := make(chan Channels)
ec := make(chan error)
htlcs, errors, err := l.r.SubscribeHtlcEvents(ctx)
if err != nil {
return nil, nil, fmt.Errorf("cannot subscribe to channel updates %w", err)
}
// translate htlc events into channels
go func() {
for {
select {
case h := <-htlcs:
channels := make(Channels, 0)
// attempt to filter on forward events
if h.GetForwardEvent() == nil {
continue
}
if h.GetIncomingChannelId() != 0 {
c, err := l.GetChannel(ctx, ChannelID(h.GetIncomingChannelId()))
if err != nil {
ec <- fmt.Errorf("cannot pull %d channel info on update %w", h.GetIncomingChannelId(), err)
break
}
channels = append(channels, c)
}
if h.GetOutgoingChannelId() != 0 {
c, err := l.GetChannel(ctx, ChannelID(h.GetOutgoingChannelId()))
if err != nil {
ec <- fmt.Errorf("cannot pull %d channel info on update %w", h.GetOutgoingChannelId(), err)
break
}
channels = append(channels, c)
}
cc <- channels
case err = <-errors:
ec <- fmt.Errorf("channel updates blip %w", err)
}
}
}()
return cc, ec, nil
}
// ForwardingHistory of node since the time give, capped at 50,000 events.
func (l LndClient) ForwardingHistory(ctx context.Context, since time.Time) ([]Forward, error) {
maxEvents := 50000
req := lndclient.ForwardingHistoryRequest{
StartTime: since,
EndTime: time.Now(),
MaxEvents: uint32(maxEvents),
}
res, err := l.c.ForwardingHistory(ctx, req)
if err != nil {
return nil, err
}
// maybe reconsider better failure method
if len(res.Events) == maxEvents {
return nil, errors.New("pulled too many events, lower time window")
}
forwards := make([]Forward, 0)
for _, f := range res.Events {
forward := Forward{
Timestamp: f.Timestamp,
ChannelIn: ChannelID(f.ChannelIn),
ChannelOut: ChannelID(f.ChannelOut),
}
forwards = append(forwards, forward)
}
return forwards, nil
}
func decodeChannelPoint(cp string) (*wire.OutPoint, error) {
split := strings.SplitN(cp, ":", 2)
hash, err := chainhash.NewHashFromStr(split[0])
if err != nil {
return nil, err
}
index, err := strconv.ParseUint(split[1], 10, 32)
if err != nil {
return nil, err
}
return &wire.OutPoint{
Hash: *hash,
Index: uint32(index),
}, nil
}