-
Notifications
You must be signed in to change notification settings - Fork 18
/
Copy pathintercept_handler.go
700 lines (632 loc) · 20 KB
/
intercept_handler.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
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
package lsps2
import (
"context"
"encoding/hex"
"log"
"math"
"strings"
"time"
"github.com/breez/lspd/chain"
"github.com/breez/lspd/common"
"github.com/breez/lspd/history"
"github.com/breez/lspd/lightning"
"github.com/breez/lspd/lsps0"
"github.com/btcsuite/btcd/wire"
)
type InterceptorConfig struct {
NodeId []byte
AdditionalChannelCapacitySat uint64
MinConfs *uint32
TargetConf uint32
FeeStrategy chain.FeeStrategy
MinPaymentSizeMsat uint64
MaxPaymentSizeMsat uint64
TimeLockDelta uint32
HtlcMinimumMsat uint64
MppTimeout time.Duration
}
type Interceptor struct {
store Lsps2Store
historyStore history.Store
openingService common.OpeningService
client lightning.Client
feeEstimator chain.FeeEstimator
config *InterceptorConfig
newPart chan *partState
registrationFetched chan *registrationFetchedEvent
paymentReady chan string
paymentFailure chan *paymentFailureEvent
paymentChanOpened chan *paymentChanOpenedEvent
inflightPayments map[string]*paymentState
}
func NewInterceptHandler(
store Lsps2Store,
historyStore history.Store,
openingService common.OpeningService,
client lightning.Client,
feeEstimator chain.FeeEstimator,
config *InterceptorConfig,
) *Interceptor {
if config.MppTimeout.Nanoseconds() == 0 {
config.MppTimeout = time.Duration(90 * time.Second)
}
return &Interceptor{
store: store,
historyStore: historyStore,
openingService: openingService,
client: client,
feeEstimator: feeEstimator,
config: config,
// TODO: make sure the chan sizes do not lead to deadlocks.
newPart: make(chan *partState, 1000),
registrationFetched: make(chan *registrationFetchedEvent, 1000),
paymentReady: make(chan string, 1000),
paymentFailure: make(chan *paymentFailureEvent, 1000),
paymentChanOpened: make(chan *paymentChanOpenedEvent, 1000),
inflightPayments: make(map[string]*paymentState),
}
}
type paymentState struct {
id string
fakeScid lightning.ShortChannelID
outgoingSumMsat uint64
paymentSizeMsat uint64
feeMsat uint64
registration *BuyRegistration
parts map[string]*partState
isFinal bool
timoutChanClosed bool
timeoutChan chan struct{}
}
func (p *paymentState) closeTimeoutChan() {
if p.timoutChanClosed {
return
}
close(p.timeoutChan)
p.timoutChanClosed = true
}
type partState struct {
req *common.InterceptRequest
resolution chan *common.InterceptResult
}
type registrationFetchedEvent struct {
paymentId string
isRegistered bool
registration *BuyRegistration
}
type paymentChanOpenedEvent struct {
paymentId string
scid lightning.ShortChannelID
channelPoint *wire.OutPoint
htlcMinimumMsat uint64
}
type paymentFailureEvent struct {
paymentId string
code common.InterceptFailureCode
}
func (i *Interceptor) Start(ctx context.Context) {
// Main event loop for stages of htlcs to be handled. Note that the event
// loop has to execute quickly, so any code running in the 'handle' methods
// must execute quickly. If there is i/o involved, or any waiting, run that
// code in a goroutine, and place an event onto the event loop to continue
// processing after the slow operation is done.
// The nice thing about an event loop is that it runs on a single thread.
// So there's no locking needed, as long as everything that needs
// synchronization goes through the event loop.
for {
select {
case part := <-i.newPart:
i.handleNewPart(part)
case ev := <-i.registrationFetched:
i.handleRegistrationFetched(ev)
case paymentId := <-i.paymentReady:
i.handlePaymentReady(paymentId)
case ev := <-i.paymentFailure:
i.handlePaymentFailure(ev.paymentId, ev.code)
case ev := <-i.paymentChanOpened:
i.handlePaymentChanOpened(ev)
}
}
}
func (i *Interceptor) handleNewPart(part *partState) {
// Get the associated payment for this part, or create a new payment if it
// doesn't exist for this part yet.
paymentId := part.req.PaymentId()
payment, paymentExisted := i.inflightPayments[paymentId]
if !paymentExisted {
payment = &paymentState{
id: paymentId,
fakeScid: part.req.Scid,
parts: make(map[string]*partState),
timeoutChan: make(chan struct{}),
}
i.inflightPayments[paymentId] = payment
}
// Check whether we already have this part, because it may have been
// replayed.
existingPart, partExisted := payment.parts[part.req.HtlcId()]
// Adds the part to the in-progress parts. Or replaces it, if it already
// exists, to make sure we always reply to the correct identifier. If a htlc
// was replayed, assume the latest event is the truth to respond to.
payment.parts[part.req.HtlcId()] = part
if partExisted {
// If the part already existed, that means it has been replayed. In this
// case the first occurence can be safely ignored, because we won't be
// able to reply to that htlc anyway. Keep the last replayed version for
// further processing. This result below tells the caller to ignore the
// htlc.
existingPart.resolution <- &common.InterceptResult{
Action: common.INTERCEPT_IGNORE,
}
return
}
// If this is the first part for this payment, setup the timeout, and fetch
// the registration.
if !paymentExisted {
go func() {
select {
case <-time.After(i.config.MppTimeout):
// Handle timeout inside the event loop, to make sure there are
// no race conditions, since this timeout watcher is running in
// a goroutine.
i.paymentFailure <- &paymentFailureEvent{
paymentId: paymentId,
code: common.FAILURE_TEMPORARY_CHANNEL_FAILURE,
}
case <-payment.timeoutChan:
// Stop listening for timeouts when the payment is ready.
}
}()
// Fetch the buy registration in a goroutine, to avoid blocking the
// event loop.
go i.fetchRegistration(part.req.PaymentId(), part.req.Scid)
}
// If the registration was already fetched, this part might complete the
// payment. Process the part. Otherwise, the part will be processed after
// the registration was fetched, as a result of 'registrationFetched'.
if payment.registration != nil {
i.processPart(payment, part)
}
}
func (i *Interceptor) processPart(payment *paymentState, part *partState) {
if payment.registration.IsComplete {
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
// Fail parts that come in after the payment is already final. To avoid
// inconsistencies in the payment state.
if payment.isFinal {
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
var err error
if payment.registration.Mode == OpeningMode_NoMppVarInvoice {
// Mode == no-MPP+var-invoice
if payment.paymentSizeMsat != 0 {
// Another part is already processed for this payment, and with
// no-MPP+var-invoice there can be only a single part, so this
// part will be failed back.
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
// If the mode is no-MPP+var-invoice, the payment size comes from
// the actual forwarded amount.
payment.paymentSizeMsat = part.req.OutgoingAmountMsat
// Make sure the minimum and maximum are not exceeded.
if payment.paymentSizeMsat > i.config.MaxPaymentSizeMsat ||
payment.paymentSizeMsat < i.config.MinPaymentSizeMsat {
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
// Make sure there is enough fee to deduct.
payment.feeMsat, err = computeOpeningFee(
payment.paymentSizeMsat,
payment.registration.OpeningFeeParams.Proportional,
payment.registration.OpeningFeeParams.MinFeeMsat,
)
if err != nil {
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
// Make sure the part fits the htlc and fee constraints.
if payment.feeMsat+i.config.HtlcMinimumMsat >
payment.paymentSizeMsat {
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
} else {
// Mode == MPP+fixed-invoice
payment.paymentSizeMsat = *payment.registration.PaymentSizeMsat
payment.feeMsat, err = computeOpeningFee(
payment.paymentSizeMsat,
payment.registration.OpeningFeeParams.Proportional,
payment.registration.OpeningFeeParams.MinFeeMsat,
)
if err != nil {
log.Printf(
"Opening fee calculation error while trying to open channel "+
"for scid %s: %v",
payment.registration.Scid.ToString(),
err,
)
i.failPart(payment, part, common.FAILURE_UNKNOWN_NEXT_PEER)
return
}
}
// Make sure the cltv delta is enough.
if int64(part.req.IncomingExpiry)-int64(part.req.OutgoingExpiry) <
int64(i.config.TimeLockDelta) {
i.failPart(payment, part, common.FAILURE_INCORRECT_CLTV_EXPIRY)
return
}
// Make sure htlc minimum is enough
if part.req.OutgoingAmountMsat < i.config.HtlcMinimumMsat {
i.failPart(payment, part, common.FAILURE_AMOUNT_BELOW_MINIMUM)
return
}
// Make sure we're not getting tricked
if part.req.IncomingAmountMsat < part.req.OutgoingAmountMsat {
i.failPart(payment, part, common.FAILURE_AMOUNT_BELOW_MINIMUM)
return
}
// Update the sum of htlcs currently in-flight.
payment.outgoingSumMsat += part.req.OutgoingAmountMsat
// If payment_size_msat is reached, the payment is ready to forward. (this
// is always true in no-MPP+var-invoice mode)
if payment.outgoingSumMsat >= payment.paymentSizeMsat {
payment.isFinal = true
i.paymentReady <- part.req.PaymentId()
}
}
// Fetches the registration from the store. If the registration exists, posts
// a registrationReady event. If it doesn't, posts a 'notRegistered' event.
func (i *Interceptor) fetchRegistration(
paymentId string,
scid lightning.ShortChannelID,
) {
registration, err := i.store.GetBuyRegistration(
context.TODO(),
scid,
)
if err != nil && err != ErrNotFound {
log.Printf(
"Failed to get buy registration for %v: %v",
uint64(scid),
err,
)
}
i.registrationFetched <- ®istrationFetchedEvent{
paymentId: paymentId,
isRegistered: err == nil,
registration: registration,
}
}
func (i *Interceptor) handleRegistrationFetched(ev *registrationFetchedEvent) {
if !ev.isRegistered {
i.finalizeAllParts(ev.paymentId, &common.InterceptResult{
Action: common.INTERCEPT_RESUME,
})
return
}
payment, ok := i.inflightPayments[ev.paymentId]
if !ok {
// Apparently the payment is already finished.
return
}
payment.registration = ev.registration
for _, part := range payment.parts {
i.processPart(payment, part)
}
}
func (i *Interceptor) handlePaymentReady(paymentId string) {
payment, ok := i.inflightPayments[paymentId]
if !ok {
// Apparently this payment is already finalized.
return
}
// TODO: Handle notifications.
// Stops the timeout listeners
payment.closeTimeoutChan()
go i.ensureChannelOpen(payment)
}
// Opens a channel to the destination and waits for the channel to become
// active. When the channel is active, sends an openChanEvent. Should be run in
// a goroutine.
func (i *Interceptor) ensureChannelOpen(payment *paymentState) {
destination, _ := hex.DecodeString(payment.registration.PeerId)
if payment.registration.ChannelPoint == nil {
validUntil, err := time.Parse(
lsps0.TIME_FORMAT,
payment.registration.OpeningFeeParams.ValidUntil,
)
if err != nil {
log.Printf(
"Failed parse validUntil '%s' for paymentId %s: %v",
payment.registration.OpeningFeeParams.ValidUntil,
payment.id,
err,
)
i.paymentFailure <- &paymentFailureEvent{
paymentId: payment.id,
code: common.FAILURE_UNKNOWN_NEXT_PEER,
}
return
}
// With expired fee params, the current chainfees are checked. If
// they're not cheaper now, fail the payment.
if time.Now().After(validUntil) &&
!i.openingService.IsCurrentChainFeeCheaper(
payment.registration.Token,
&payment.registration.OpeningFeeParams,
) {
log.Printf("LSPS2: Intercepted expired payment registration. "+
"Failing payment. scid: %s, valid until: %s, destination: %s",
payment.fakeScid.ToString(),
payment.registration.OpeningFeeParams.ValidUntil,
payment.registration.PeerId,
)
i.paymentFailure <- &paymentFailureEvent{
paymentId: payment.id,
code: common.FAILURE_UNKNOWN_NEXT_PEER,
}
return
}
fee, err := i.feeEstimator.EstimateFeeRate(
context.Background(),
i.config.FeeStrategy,
)
if err != nil || fee == nil {
log.Printf("Error estimating chain fee, fallback to target conf: %v", err)
fee = &chain.FeeEstimation{
TargetConf: &i.config.TargetConf,
}
}
capacity := ((payment.paymentSizeMsat - payment.feeMsat +
999) / 1000) + i.config.AdditionalChannelCapacitySat
log.Printf(
"LSPS2: Opening zero conf channel. Destination: %x, capacity: %v, "+
"fee: %s",
destination,
capacity,
fee.String(),
)
channelPoint, err := i.client.OpenChannel(&lightning.OpenChannelRequest{
Destination: destination,
CapacitySat: uint64(capacity),
MinConfs: i.config.MinConfs,
FeeSatPerVByte: fee.SatPerVByte,
TargetConf: fee.TargetConf,
})
if err != nil {
log.Printf(
"LSPS2 openChannel: client.OpenChannel(%x, %v) error: %v",
destination,
capacity,
err,
)
code := common.FAILURE_UNKNOWN_NEXT_PEER
if strings.Contains(err.Error(), "not enough funds") {
code = common.FAILURE_TEMPORARY_CHANNEL_FAILURE
}
// TODO: Verify that a client disconnect before receiving
// funding_signed doesn't cause the OpenChannel call to error.
// unknown_next_peer should only be returned if the client rejects
// the channel, or the channel cannot be opened at all. If the
// client disconnects before receiving funding_signed,
// temporary_channel_failure should be returned.
i.paymentFailure <- &paymentFailureEvent{
paymentId: payment.id,
code: code,
}
return
}
err = i.store.SetChannelOpened(
context.TODO(),
&ChannelOpened{
RegistrationId: payment.registration.Id,
Outpoint: channelPoint,
FeeMsat: payment.feeMsat,
PaymentSizeMsat: payment.paymentSizeMsat,
},
)
if err != nil {
log.Printf(
"LSPS2 openChannel: store.SetOpenedChannel(%d, %s) error: %v",
payment.registration.Id,
channelPoint.String(),
err,
)
i.paymentFailure <- &paymentFailureEvent{
paymentId: payment.id,
code: common.FAILURE_TEMPORARY_CHANNEL_FAILURE,
}
return
}
payment.registration.ChannelPoint = channelPoint
// TODO: Send open channel email notification.
}
deadline := time.Now().Add(time.Minute)
// Wait for the channel to open.
for {
chanResult, _ := i.client.GetChannel(
destination,
*payment.registration.ChannelPoint,
)
if chanResult == nil {
select {
case <-time.After(time.Second):
continue
case <-time.After(time.Until(deadline)):
i.paymentFailure <- &paymentFailureEvent{
paymentId: payment.id,
code: common.FAILURE_TEMPORARY_CHANNEL_FAILURE,
}
return
}
}
log.Printf(
"Got new channel for forward successfully. scid alias: %v, "+
"confirmed scid: %v",
chanResult.AliasScid.ToString(),
chanResult.ConfirmedScid.ToString(),
)
var scid *lightning.ShortChannelID
if chanResult.ConfirmedScid == nil {
if chanResult.AliasScid == nil {
log.Printf("Error: GetChannel: Both confirmed scid and alias scid are nil: %+v", chanResult)
<-time.After(1 * time.Second)
continue
}
scid = chanResult.AliasScid
} else {
scid = chanResult.ConfirmedScid
}
err := i.historyStore.UpdateChannels(context.TODO(), []*history.ChannelUpdate{{
NodeID: i.config.NodeId,
PeerId: destination,
AliasScid: chanResult.AliasScid,
ConfirmedScid: chanResult.ConfirmedScid,
ChannelPoint: payment.registration.ChannelPoint,
LastUpdate: time.Now(),
}})
if err != nil {
// Don't break here, this is not critical.
log.Printf("failed to insert newly opened channel in history store. %v", payment.registration.ChannelPoint.String())
}
i.paymentChanOpened <- &paymentChanOpenedEvent{
paymentId: payment.id,
scid: *scid,
channelPoint: payment.registration.ChannelPoint,
htlcMinimumMsat: chanResult.HtlcMinimumMsat,
}
break
}
}
func (i *Interceptor) handlePaymentChanOpened(event *paymentChanOpenedEvent) {
payment, ok := i.inflightPayments[event.paymentId]
if !ok {
// Apparently this payment is already finalized.
return
}
feeRemainingMsat := payment.feeMsat
destination, _ := hex.DecodeString(payment.registration.PeerId)
// Deduct the lsp fee from the parts to forward.
resolutions := []*struct {
part *partState
resolution *common.InterceptResult
}{}
for _, part := range payment.parts {
deductMsat := uint64(math.Min(
float64(feeRemainingMsat),
float64(part.req.OutgoingAmountMsat-event.htlcMinimumMsat),
))
feeRemainingMsat -= deductMsat
amountMsat := part.req.OutgoingAmountMsat - deductMsat
var feeMsat *uint64
if deductMsat > 0 {
feeMsat = &deductMsat
}
resolutions = append(resolutions, &struct {
part *partState
resolution *common.InterceptResult
}{
part: part,
resolution: &common.InterceptResult{
Action: common.INTERCEPT_RESUME_WITH_ONION,
Destination: destination,
ChannelPoint: event.channelPoint,
AmountMsat: amountMsat,
FeeMsat: feeMsat,
Scid: event.scid,
},
})
}
if feeRemainingMsat > 0 {
// It is possible this case happens if the htlc_minimum_msat is larger
// than 1. We might not be able to deduct the opening fees from the
// payment entirely. This is an edge case, and we'll fail the payment.
log.Printf(
"After deducting fees from payment parts, there was still fee "+
"remaining. payment id: %s, fee remaining msat: %d. Failing "+
"payment.",
event.paymentId,
feeRemainingMsat,
)
// TODO: Verify temporary_channel_failure is the way to go here, maybe
// unknown_next_peer is more appropriate.
i.paymentFailure <- &paymentFailureEvent{
paymentId: event.paymentId,
code: common.FAILURE_TEMPORARY_CHANNEL_FAILURE,
}
return
}
for _, resolution := range resolutions {
resolution.part.resolution <- resolution.resolution
}
now := time.Now()
payment.registration.IsComplete = true
go func() {
i.store.SetCompleted(context.TODO(), payment.registration.Id)
for _, resolution := range resolutions {
i.historyStore.AddOpenChannelHtlc(context.TODO(), &history.OpenChannelHtlc{
NodeId: i.config.NodeId,
PeerId: destination,
ChannelPoint: event.channelPoint,
OriginalAmountMsat: resolution.part.req.OutgoingAmountMsat,
ForwardAmountMsat: resolution.resolution.AmountMsat,
IncomingAmountMsat: resolution.part.req.IncomingAmountMsat,
ForwardTime: now,
})
}
}()
delete(i.inflightPayments, event.paymentId)
}
func (i *Interceptor) handlePaymentFailure(
paymentId string,
code common.InterceptFailureCode,
) {
i.finalizeAllParts(paymentId, &common.InterceptResult{
Action: common.INTERCEPT_FAIL_HTLC_WITH_CODE,
FailureCode: code,
})
}
func (i *Interceptor) finalizeAllParts(
paymentId string,
result *common.InterceptResult,
) {
payment, ok := i.inflightPayments[paymentId]
if !ok {
// Apparently this payment is already finalized.
return
}
// Stops the timeout listeners
payment.closeTimeoutChan()
for _, part := range payment.parts {
part.resolution <- result
}
delete(i.inflightPayments, paymentId)
}
func (i *Interceptor) Intercept(req common.InterceptRequest) common.InterceptResult {
resolution := make(chan *common.InterceptResult, 1)
i.newPart <- &partState{
req: &req,
resolution: resolution,
}
res := <-resolution
return *res
}
func (i *Interceptor) failPart(
payment *paymentState,
part *partState,
code common.InterceptFailureCode,
) {
part.resolution <- &common.InterceptResult{
Action: common.INTERCEPT_FAIL_HTLC_WITH_CODE,
FailureCode: code,
}
delete(payment.parts, part.req.HtlcId())
if len(payment.parts) == 0 {
payment.closeTimeoutChan()
delete(i.inflightPayments, part.req.PaymentId())
}
}