forked from lightningnetwork/lnd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
utxonursery.go
1518 lines (1280 loc) · 51.1 KB
/
utxonursery.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
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package lnd
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"sync"
"sync/atomic"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcutil"
"github.com/davecgh/go-spew/spew"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/channeldb"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/sweep"
)
// SUMMARY OF OUTPUT STATES
//
// - CRIB
// - SerializedType: babyOutput
// - OriginalOutputType: HTLC
// - Awaiting: First-stage HTLC CLTV expiry
// - HeightIndexEntry: Absolute block height of CLTV expiry.
// - NextState: KNDR
// - PSCL
// - SerializedType: kidOutput
// - OriginalOutputType: Commitment
// - Awaiting: Confirmation of commitment txn
// - HeightIndexEntry: None.
// - NextState: KNDR
// - KNDR
// - SerializedType: kidOutput
// - OriginalOutputType: Commitment or HTLC
// - Awaiting: Commitment CSV expiry or second-stage HTLC CSV expiry.
// - HeightIndexEntry: Input confirmation height + relative CSV delay
// - NextState: GRAD
// - GRAD:
// - SerializedType: kidOutput
// - OriginalOutputType: Commitment or HTLC
// - Awaiting: All other outputs in channel to become GRAD.
// - NextState: Mark channel fully closed in channeldb and remove.
//
// DESCRIPTION OF OUTPUT STATES
//
// TODO(roasbeef): update comment with both new output types
//
// - CRIB (babyOutput) outputs are two-stage htlc outputs that are initially
// locked using a CLTV delay, followed by a CSV delay. The first stage of a
// crib output requires broadcasting a presigned htlc timeout txn generated
// by the wallet after an absolute expiry height. Since the timeout txns are
// predetermined, they cannot be batched after-the-fact, meaning that all
// CRIB outputs are broadcast and confirmed independently. After the first
// stage is complete, a CRIB output is moved to the KNDR state, which will
// finishing sweeping the second-layer CSV delay.
//
// - PSCL (kidOutput) outputs are commitment outputs locked under a CSV delay.
// These outputs are stored temporarily in this state until the commitment
// transaction confirms, as this solidifies an absolute height that the
// relative time lock will expire. Once this maturity height is determined,
// the PSCL output is moved into KNDR.
//
// - KNDR (kidOutput) outputs are CSV delayed outputs for which the maturity
// height has been fully determined. This results from having received
// confirmation of the UTXO we are trying to spend, contained in either the
// commitment txn or htlc timeout txn. Once the maturity height is reached,
// the utxo nursery will sweep all KNDR outputs scheduled for that height
// using a single txn.
//
// - GRAD (kidOutput) outputs are KNDR outputs that have successfully been
// swept into the user's wallet. A channel is considered mature once all of
// its outputs, including two-stage htlcs, have entered the GRAD state,
// indicating that it safe to mark the channel as fully closed.
//
//
// OUTPUT STATE TRANSITIONS IN UTXO NURSERY
//
// ┌────────────────┐ ┌──────────────┐
// │ Commit Outputs │ │ HTLC Outputs │
// └────────────────┘ └──────────────┘
// │ │
// │ │
// │ │ UTXO NURSERY
// ┌───────────┼────────────────┬───────────┼───────────────────────────────┐
// │ │ │ │
// │ │ │ │ │
// │ │ │ CLTV-Delayed │
// │ │ │ V babyOutputs │
// │ │ ┌──────┐ │
// │ │ │ │ CRIB │ │
// │ │ └──────┘ │
// │ │ │ │ │
// │ │ │ │
// │ │ │ | │
// │ │ V Wait CLTV │
// │ │ │ [ ] + │
// │ │ | Publish Txn │
// │ │ │ │ │
// │ │ │ │
// │ │ │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐ │
// │ │ ( ) waitForTimeoutConf │
// │ │ │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ │
// │ │ │ │
// │ │ │ │ │
// │ │ │ │
// │ V │ │ │
// │ ┌──────┐ │ │
// │ │ PSCL │ └ ── ── ─┼ ── ── ── ── ── ── ── ─┤
// │ └──────┘ │ │
// │ │ │ │
// │ │ │ │
// │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐ │ CSV-Delayed │
// │ ( ) waitForCommitConf │ kidOutputs │
// │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘ │ │
// │ │ │ │
// │ │ │ │
// │ │ V │
// │ │ ┌──────┐ │
// │ └─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─▶│ KNDR │ │
// │ └──────┘ │
// │ │ │
// │ │ │
// │ | │
// │ V Wait CSV │
// │ [ ] + │
// │ | Publish Txn │
// │ │ │
// │ │ │
// │ V ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┐ │
// │ ( ) waitForSweepConf │
// │ | └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ┘ │
// │ │ │
// │ │ │
// │ V │
// │ ┌──────┐ │
// │ │ GRAD │ │
// │ └──────┘ │
// │ │ │
// │ │ │
// │ │ │
// └────────────────────────────────────────┼───────────────────────────────┘
// │
// │
// │
// │
// V
// ┌────────────────┐
// │ Wallet Outputs │
// └────────────────┘
var byteOrder = binary.BigEndian
const (
// kgtnOutputConfTarget is the default confirmation target we'll use for
// sweeps of CSV delayed outputs.
kgtnOutputConfTarget = 6
)
var (
// ErrContractNotFound is returned when the nursery is unable to
// retrieve information about a queried contract.
ErrContractNotFound = fmt.Errorf("unable to locate contract")
)
// NurseryConfig abstracts the required subsystems used by the utxo nursery. An
// instance of NurseryConfig is passed to newUtxoNursery during instantiation.
type NurseryConfig struct {
// ChainIO is used by the utxo nursery to determine the current block
// height, which drives the incubation of the nursery's outputs.
ChainIO lnwallet.BlockChainIO
// ConfDepth is the number of blocks the nursery store waits before
// determining outputs in the chain as confirmed.
ConfDepth uint32
// FetchClosedChannels provides access to a user's channels, such that
// they can be marked fully closed after incubation has concluded.
FetchClosedChannels func(pendingOnly bool) (
[]*channeldb.ChannelCloseSummary, error)
// FetchClosedChannel provides access to the close summary to extract a
// height hint from.
FetchClosedChannel func(chanID *wire.OutPoint) (
*channeldb.ChannelCloseSummary, error)
// Notifier provides the utxo nursery the ability to subscribe to
// transaction confirmation events, which advance outputs through their
// persistence state transitions.
Notifier chainntnfs.ChainNotifier
// PublishTransaction facilitates the process of broadcasting a signed
// transaction to the appropriate network.
PublishTransaction func(*wire.MsgTx) error
// Store provides access to and modification of the persistent state
// maintained about the utxo nursery's incubating outputs.
Store NurseryStore
// Sweep sweeps an input back to the wallet.
SweepInput func(input.Input, sweep.FeePreference) (chan sweep.Result, error)
}
// utxoNursery is a system dedicated to incubating time-locked outputs created
// by the broadcast of a commitment transaction either by us, or the remote
// peer. The nursery accepts outputs and "incubates" them until they've reached
// maturity, then sweep the outputs into the source wallet. An output is
// considered mature after the relative time-lock within the pkScript has
// passed. As outputs reach their maturity age, they're swept in batches into
// the source wallet, returning the outputs so they can be used within future
// channels, or regular Bitcoin transactions.
type utxoNursery struct {
started uint32 // To be used atomically.
stopped uint32 // To be used atomically.
cfg *NurseryConfig
mu sync.Mutex
bestHeight uint32
quit chan struct{}
wg sync.WaitGroup
}
// newUtxoNursery creates a new instance of the utxoNursery from a
// ChainNotifier and LightningWallet instance.
func newUtxoNursery(cfg *NurseryConfig) *utxoNursery {
return &utxoNursery{
cfg: cfg,
quit: make(chan struct{}),
}
}
// Start launches all goroutines the utxoNursery needs to properly carry out
// its duties.
func (u *utxoNursery) Start() error {
if !atomic.CompareAndSwapUint32(&u.started, 0, 1) {
return nil
}
utxnLog.Tracef("Starting UTXO nursery")
// Retrieve the currently best known block. This is needed to have the
// state machine catch up with the blocks we missed when we were down.
bestHash, bestHeight, err := u.cfg.ChainIO.GetBestBlock()
if err != nil {
return err
}
// Set best known height to schedule late registrations properly.
atomic.StoreUint32(&u.bestHeight, uint32(bestHeight))
// 2. Flush all fully-graduated channels from the pipeline.
// Load any pending close channels, which represents the super set of
// all channels that may still be incubating.
pendingCloseChans, err := u.cfg.FetchClosedChannels(true)
if err != nil {
return err
}
// Ensure that all mature channels have been marked as fully closed in
// the channeldb.
for _, pendingClose := range pendingCloseChans {
err := u.closeAndRemoveIfMature(&pendingClose.ChanPoint)
if err != nil {
return err
}
}
// TODO(conner): check if any fully closed channels can be removed from
// utxn.
// 2. Restart spend ntfns for any preschool outputs, which are waiting
// for the force closed commitment txn to confirm, or any second-layer
// HTLC success transactions.
//
// NOTE: The next two steps *may* spawn go routines, thus from this
// point forward, we must close the nursery's quit channel if we detect
// any failures during startup to ensure they terminate.
if err := u.reloadPreschool(); err != nil {
close(u.quit)
return err
}
// 3. Replay all crib and kindergarten outputs up to the current best
// height.
if err := u.reloadClasses(uint32(bestHeight)); err != nil {
close(u.quit)
return err
}
// Start watching for new blocks, as this will drive the nursery store's
// state machine.
newBlockChan, err := u.cfg.Notifier.RegisterBlockEpochNtfn(&chainntnfs.BlockEpoch{
Height: bestHeight,
Hash: bestHash,
})
if err != nil {
close(u.quit)
return err
}
u.wg.Add(1)
go u.incubator(newBlockChan)
return nil
}
// Stop gracefully shuts down any lingering goroutines launched during normal
// operation of the utxoNursery.
func (u *utxoNursery) Stop() error {
if !atomic.CompareAndSwapUint32(&u.stopped, 0, 1) {
return nil
}
utxnLog.Infof("UTXO nursery shutting down")
close(u.quit)
u.wg.Wait()
return nil
}
// IncubateOutputs sends a request to the utxoNursery to incubate a set of
// outputs from an existing commitment transaction. Outputs need to incubate if
// they're CLTV absolute time locked, or if they're CSV relative time locked.
// Once all outputs reach maturity, they'll be swept back into the wallet.
func (u *utxoNursery) IncubateOutputs(chanPoint wire.OutPoint,
commitResolution *lnwallet.CommitOutputResolution,
outgoingHtlcs []lnwallet.OutgoingHtlcResolution,
incomingHtlcs []lnwallet.IncomingHtlcResolution,
broadcastHeight uint32) error {
// Add to wait group because nursery might shut down during execution of
// this function. Otherwise it could happen that nursery thinks it is
// shut down, but in this function new goroutines were started and stay
// around.
u.wg.Add(1)
defer u.wg.Done()
// Check quit channel for the case where the waitgroup wait was finished
// right before this function's add call was made.
select {
case <-u.quit:
return fmt.Errorf("nursery shutting down")
default:
}
numHtlcs := len(incomingHtlcs) + len(outgoingHtlcs)
var (
hasCommit bool
// Kid outputs can be swept after an initial confirmation
// followed by a maturity period.Baby outputs are two stage and
// will need to wait for an absolute time out to reach a
// confirmation, then require a relative confirmation delay.
kidOutputs = make([]kidOutput, 0, 1+len(incomingHtlcs))
babyOutputs = make([]babyOutput, 0, len(outgoingHtlcs))
)
// 1. Build all the spendable outputs that we will try to incubate.
// It could be that our to-self output was below the dust limit. In
// that case the commit resolution would be nil and we would not have
// that output to incubate.
if commitResolution != nil {
hasCommit = true
selfOutput := makeKidOutput(
&commitResolution.SelfOutPoint,
&chanPoint,
commitResolution.MaturityDelay,
input.CommitmentTimeLock,
&commitResolution.SelfOutputSignDesc,
0,
)
// We'll skip any zero valued outputs as this indicates we
// don't have a settled balance within the commitment
// transaction.
if selfOutput.Amount() > 0 {
kidOutputs = append(kidOutputs, selfOutput)
}
}
// TODO(roasbeef): query and see if we already have, if so don't add?
// For each incoming HTLC, we'll register a kid output marked as a
// second-layer HTLC output. We effectively skip the baby stage (as the
// timelock is zero), and enter the kid stage.
for _, htlcRes := range incomingHtlcs {
htlcOutput := makeKidOutput(
&htlcRes.ClaimOutpoint, &chanPoint, htlcRes.CsvDelay,
input.HtlcAcceptedSuccessSecondLevel,
&htlcRes.SweepSignDesc, 0,
)
if htlcOutput.Amount() > 0 {
kidOutputs = append(kidOutputs, htlcOutput)
}
}
// For each outgoing HTLC, we'll create a baby output. If this is our
// commitment transaction, then we'll broadcast a second-layer
// transaction to transition to a kid output. Otherwise, we'll directly
// spend once the CLTV delay us up.
for _, htlcRes := range outgoingHtlcs {
// If this HTLC is on our commitment transaction, then it'll be
// a baby output as we need to go to the second level to sweep
// it.
if htlcRes.SignedTimeoutTx != nil {
htlcOutput := makeBabyOutput(&chanPoint, &htlcRes)
if htlcOutput.Amount() > 0 {
babyOutputs = append(babyOutputs, htlcOutput)
}
continue
}
// Otherwise, this is actually a kid output as we can sweep it
// once the commitment transaction confirms, and the absolute
// CLTV lock has expired. We set the CSV delay to zero to
// indicate this is actually a CLTV output.
htlcOutput := makeKidOutput(
&htlcRes.ClaimOutpoint, &chanPoint, 0,
input.HtlcOfferedRemoteTimeout,
&htlcRes.SweepSignDesc, htlcRes.Expiry,
)
kidOutputs = append(kidOutputs, htlcOutput)
}
// TODO(roasbeef): if want to handle outgoing on remote commit
// * need ability to cancel in the case that we learn of pre-image or
// remote party pulls
utxnLog.Infof("Incubating Channel(%s) has-commit=%v, num-htlcs=%d",
chanPoint, hasCommit, numHtlcs)
u.mu.Lock()
defer u.mu.Unlock()
// 2. Persist the outputs we intended to sweep in the nursery store
if err := u.cfg.Store.Incubate(kidOutputs, babyOutputs); err != nil {
utxnLog.Errorf("unable to begin incubation of Channel(%s): %v",
chanPoint, err)
return err
}
// As an intermediate step, we'll now check to see if any of the baby
// outputs has actually _already_ expired. This may be the case if
// blocks were mined while we processed this message.
_, bestHeight, err := u.cfg.ChainIO.GetBestBlock()
if err != nil {
return err
}
// We'll examine all the baby outputs just inserted into the database,
// if the output has already expired, then we'll *immediately* sweep
// it. This may happen if the caller raced a block to call this method.
for i, babyOutput := range babyOutputs {
if uint32(bestHeight) >= babyOutput.expiry {
err = u.sweepCribOutput(
babyOutput.expiry, &babyOutputs[i],
)
if err != nil {
return err
}
}
}
// 3. If we are incubating any preschool outputs, register for a
// confirmation notification that will transition it to the
// kindergarten bucket.
if len(kidOutputs) != 0 {
for i := range kidOutputs {
err := u.registerPreschoolConf(
&kidOutputs[i], broadcastHeight,
)
if err != nil {
return err
}
}
}
return nil
}
// NurseryReport attempts to return a nursery report stored for the target
// outpoint. A nursery report details the maturity/sweeping progress for a
// contract that was previously force closed. If a report entry for the target
// chanPoint is unable to be constructed, then an error will be returned.
func (u *utxoNursery) NurseryReport(
chanPoint *wire.OutPoint) (*contractMaturityReport, error) {
u.mu.Lock()
defer u.mu.Unlock()
utxnLog.Infof("NurseryReport: building nursery report for channel %v",
chanPoint)
report := &contractMaturityReport{}
if err := u.cfg.Store.ForChanOutputs(chanPoint, func(k, v []byte) error {
switch {
case bytes.HasPrefix(k, cribPrefix):
// Cribs outputs are the only kind currently stored as
// baby outputs.
var baby babyOutput
err := baby.Decode(bytes.NewReader(v))
if err != nil {
return err
}
// Each crib output represents a stage one htlc, and
// will contribute towards the limbo balance.
report.AddLimboStage1TimeoutHtlc(&baby)
case bytes.HasPrefix(k, psclPrefix),
bytes.HasPrefix(k, kndrPrefix),
bytes.HasPrefix(k, gradPrefix):
// All others states can be deserialized as kid outputs.
var kid kidOutput
err := kid.Decode(bytes.NewReader(v))
if err != nil {
return err
}
// Now, use the state prefixes to determine how the
// this output should be represented in the nursery
// report. An output's funds are always in limbo until
// reaching the graduate state.
switch {
case bytes.HasPrefix(k, psclPrefix):
// Preschool outputs are awaiting the
// confirmation of the commitment transaction.
switch kid.WitnessType() {
case input.CommitmentTimeLock:
report.AddLimboCommitment(&kid)
case input.HtlcAcceptedSuccessSecondLevel:
// An HTLC output on our commitment transaction
// where the second-layer transaction hasn't
// yet confirmed.
report.AddLimboStage1SuccessHtlc(&kid)
case input.HtlcOfferedRemoteTimeout:
// This is an HTLC output on the
// commitment transaction of the remote
// party. We are waiting for the CLTV
// timelock expire.
report.AddLimboDirectHtlc(&kid)
}
case bytes.HasPrefix(k, kndrPrefix):
// Kindergarten outputs may originate from
// either the commitment transaction or an htlc.
// We can distinguish them via their witness
// types.
switch kid.WitnessType() {
case input.CommitmentTimeLock:
// The commitment transaction has been
// confirmed, and we are waiting the CSV
// delay to expire.
report.AddLimboCommitment(&kid)
case input.HtlcOfferedRemoteTimeout:
// This is an HTLC output on the
// commitment transaction of the remote
// party. The CLTV timelock has
// expired, and we only need to sweep
// it.
report.AddLimboDirectHtlc(&kid)
case input.HtlcAcceptedSuccessSecondLevel:
fallthrough
case input.HtlcOfferedTimeoutSecondLevel:
// The htlc timeout or success
// transaction has confirmed, and the
// CSV delay has begun ticking.
report.AddLimboStage2Htlc(&kid)
}
case bytes.HasPrefix(k, gradPrefix):
// Graduate outputs are those whose funds have
// been swept back into the wallet. Each output
// will contribute towards the recovered
// balance.
switch kid.WitnessType() {
case input.CommitmentTimeLock:
// The commitment output was
// successfully swept back into a
// regular p2wkh output.
report.AddRecoveredCommitment(&kid)
case input.HtlcAcceptedSuccessSecondLevel:
fallthrough
case input.HtlcOfferedTimeoutSecondLevel:
fallthrough
case input.HtlcOfferedRemoteTimeout:
// This htlc output successfully
// resides in a p2wkh output belonging
// to the user.
report.AddRecoveredHtlc(&kid)
}
}
default:
}
return nil
}); err != nil {
return nil, err
}
return report, nil
}
// reloadPreschool re-initializes the chain notifier with all of the outputs
// that had been saved to the "preschool" database bucket prior to shutdown.
func (u *utxoNursery) reloadPreschool() error {
psclOutputs, err := u.cfg.Store.FetchPreschools()
if err != nil {
return err
}
// For each of the preschool outputs stored in the nursery store, load
// its close summary from disk so that we can get an accurate height
// hint from which to start our range for spend notifications.
for i := range psclOutputs {
kid := &psclOutputs[i]
chanPoint := kid.OriginChanPoint()
// Load the close summary for this output's channel point.
closeSummary, err := u.cfg.FetchClosedChannel(chanPoint)
if err == channeldb.ErrClosedChannelNotFound {
// This should never happen since the close summary
// should only be removed after the channel has been
// swept completely.
utxnLog.Warnf("Close summary not found for "+
"chan_point=%v, can't determine height hint"+
"to sweep commit txn", chanPoint)
continue
} else if err != nil {
return err
}
// Use the close height from the channel summary as our height
// hint to drive our spend notifications, with our confirmation
// depth as a buffer for reorgs.
heightHint := closeSummary.CloseHeight - u.cfg.ConfDepth
err = u.registerPreschoolConf(kid, heightHint)
if err != nil {
return err
}
}
return nil
}
// reloadClasses reinitializes any height-dependent state transitions for which
// the utxonursery has not received confirmation, and replays the graduation of
// all kindergarten and crib outputs for all heights up to the current block.
// This allows the nursery to reinitialize all state to continue sweeping
// outputs, even in the event that we missed blocks while offline. reloadClasses
// is called during the startup of the UTXO Nursery.
func (u *utxoNursery) reloadClasses(bestHeight uint32) error {
// Loading all active heights up to and including the current block.
activeHeights, err := u.cfg.Store.HeightsBelowOrEqual(
uint32(bestHeight))
if err != nil {
return err
}
// Return early if nothing to sweep.
if len(activeHeights) == 0 {
return nil
}
utxnLog.Infof("(Re)-sweeping %d heights below height=%d",
len(activeHeights), bestHeight)
// Attempt to re-register notifications for any outputs still at these
// heights.
for _, classHeight := range activeHeights {
utxnLog.Debugf("Attempting to sweep outputs at height=%v",
classHeight)
if err = u.graduateClass(classHeight); err != nil {
utxnLog.Errorf("Failed to sweep outputs at "+
"height=%v: %v", classHeight, err)
return err
}
}
utxnLog.Infof("UTXO Nursery is now fully synced")
return nil
}
// incubator is tasked with driving all state transitions that are dependent on
// the current height of the blockchain. As new blocks arrive, the incubator
// will attempt spend outputs at the latest height. The asynchronous
// confirmation of these spends will either 1) move a crib output into the
// kindergarten bucket or 2) move a kindergarten output into the graduated
// bucket.
func (u *utxoNursery) incubator(newBlockChan *chainntnfs.BlockEpochEvent) {
defer u.wg.Done()
defer newBlockChan.Cancel()
for {
select {
case epoch, ok := <-newBlockChan.Epochs:
// If the epoch channel has been closed, then the
// ChainNotifier is exiting which means the daemon is
// as well. Therefore, we exit early also in order to
// ensure the daemon shuts down gracefully, yet
// swiftly.
if !ok {
return
}
// TODO(roasbeef): if the BlockChainIO is rescanning
// will give stale data
// A new block has just been connected to the main
// chain, which means we might be able to graduate crib
// or kindergarten outputs at this height. This involves
// broadcasting any presigned htlc timeout txns, as well
// as signing and broadcasting a sweep txn that spends
// from all kindergarten outputs at this height.
height := uint32(epoch.Height)
// Update best known block height for late registrations
// to be scheduled properly.
atomic.StoreUint32(&u.bestHeight, height)
if err := u.graduateClass(height); err != nil {
utxnLog.Errorf("error while graduating "+
"class at height=%d: %v", height, err)
// TODO(conner): signal fatal error to daemon
}
case <-u.quit:
return
}
}
}
// graduateClass handles the steps involved in spending outputs whose CSV or
// CLTV delay expires at the nursery's current height. This method is called
// each time a new block arrives, or during startup to catch up on heights we
// may have missed while the nursery was offline.
func (u *utxoNursery) graduateClass(classHeight uint32) error {
// Record this height as the nursery's current best height.
u.mu.Lock()
defer u.mu.Unlock()
// Fetch all information about the crib and kindergarten outputs at
// this height.
kgtnOutputs, cribOutputs, err := u.cfg.Store.FetchClass(
classHeight)
if err != nil {
return err
}
utxnLog.Infof("Attempting to graduate height=%v: num_kids=%v, "+
"num_babies=%v", classHeight, len(kgtnOutputs), len(cribOutputs))
// Offer the outputs to the sweeper and set up notifications that will
// transition the swept kindergarten outputs and cltvCrib into graduated
// outputs.
if len(kgtnOutputs) > 0 {
if err := u.sweepMatureOutputs(classHeight, kgtnOutputs); err != nil {
utxnLog.Errorf("Failed to sweep %d kindergarten "+
"outputs at height=%d: %v",
len(kgtnOutputs), classHeight, err)
return err
}
}
// Now, we broadcast all pre-signed htlc txns from the csv crib outputs
// at this height.
for i := range cribOutputs {
err := u.sweepCribOutput(classHeight, &cribOutputs[i])
if err != nil {
utxnLog.Errorf("Failed to sweep first-stage HTLC "+
"(CLTV-delayed) output %v",
cribOutputs[i].OutPoint())
return err
}
}
return nil
}
// sweepMatureOutputs generates and broadcasts the transaction that transfers
// control of funds from a prior channel commitment transaction to the user's
// wallet. The outputs swept were previously time locked (either absolute or
// relative), but are not mature enough to sweep into the wallet.
func (u *utxoNursery) sweepMatureOutputs(classHeight uint32,
kgtnOutputs []kidOutput) error {
utxnLog.Infof("Sweeping %v CSV-delayed outputs with sweep tx for "+
"height %v", len(kgtnOutputs), classHeight)
feePref := sweep.FeePreference{ConfTarget: kgtnOutputConfTarget}
for _, output := range kgtnOutputs {
// Create local copy to prevent pointer to loop variable to be
// passed in with disastrous consequences.
local := output
resultChan, err := u.cfg.SweepInput(&local, feePref)
if err != nil {
return err
}
u.wg.Add(1)
go u.waitForSweepConf(classHeight, &local, resultChan)
}
return nil
}
// waitForSweepConf watches for the confirmation of a sweep transaction
// containing a batch of kindergarten outputs. Once confirmation has been
// received, the nursery will mark those outputs as fully graduated, and proceed
// to mark any mature channels as fully closed in channeldb.
// NOTE(conner): this method MUST be called as a go routine.
func (u *utxoNursery) waitForSweepConf(classHeight uint32,
output *kidOutput, resultChan chan sweep.Result) {
defer u.wg.Done()
select {
case result, ok := <-resultChan:
if !ok {
utxnLog.Errorf("Notification chan closed, can't" +
" advance graduating output")
return
}
// In case of a remote spend, still graduate the output. There
// is no way to sweep it anymore.
if result.Err == sweep.ErrRemoteSpend {
utxnLog.Infof("Output %v was spend by remote party",
output.OutPoint())
break
}
if result.Err != nil {
utxnLog.Errorf("Failed to sweep %v at "+
"height=%d", output.OutPoint(),
classHeight)
return
}
case <-u.quit:
return
}
u.mu.Lock()
defer u.mu.Unlock()
// TODO(conner): add retry logic?
// Mark the confirmed kindergarten output as graduated.
if err := u.cfg.Store.GraduateKinder(classHeight, output); err != nil {
utxnLog.Errorf("Unable to graduate kindergarten output %v: %v",
output.OutPoint(), err)
return
}
utxnLog.Infof("Graduated kindergarten output from height=%d",
classHeight)
// Attempt to close the channel, only doing so if all of the channel's
// outputs have been graduated.
chanPoint := output.OriginChanPoint()
if err := u.closeAndRemoveIfMature(chanPoint); err != nil {
utxnLog.Errorf("Failed to close and remove channel %v",
*chanPoint)
return
}
}
// sweepCribOutput broadcasts the crib output's htlc timeout txn, and sets up a
// notification that will advance it to the kindergarten bucket upon
// confirmation.
func (u *utxoNursery) sweepCribOutput(classHeight uint32, baby *babyOutput) error {
utxnLog.Infof("Publishing CLTV-delayed HTLC output using timeout tx "+
"(txid=%v): %v", baby.timeoutTx.TxHash(),
newLogClosure(func() string {
return spew.Sdump(baby.timeoutTx)
}),
)
// We'll now broadcast the HTLC transaction, then wait for it to be
// confirmed before transitioning it to kindergarten.
err := u.cfg.PublishTransaction(baby.timeoutTx)
if err != nil && err != lnwallet.ErrDoubleSpend {
utxnLog.Errorf("Unable to broadcast baby tx: "+
"%v, %v", err, spew.Sdump(baby.timeoutTx))
return err
}
return u.registerTimeoutConf(baby, classHeight)
}
// registerTimeoutConf is responsible for subscribing to confirmation
// notification for an htlc timeout transaction. If successful, a goroutine
// will be spawned that will transition the provided baby output into the
// kindergarten state within the nursery store.
func (u *utxoNursery) registerTimeoutConf(baby *babyOutput, heightHint uint32) error {
birthTxID := baby.timeoutTx.TxHash()
// Register for the confirmation of presigned htlc txn.
confChan, err := u.cfg.Notifier.RegisterConfirmationsNtfn(
&birthTxID, baby.timeoutTx.TxOut[0].PkScript, u.cfg.ConfDepth,
heightHint,
)
if err != nil {
return err
}
utxnLog.Infof("Htlc output %v registered for promotion "+
"notification.", baby.OutPoint())
u.wg.Add(1)
go u.waitForTimeoutConf(baby, confChan)
return nil
}
// waitForTimeoutConf watches for the confirmation of an htlc timeout
// transaction, and attempts to move the htlc output from the crib bucket to the
// kindergarten bucket upon success.
func (u *utxoNursery) waitForTimeoutConf(baby *babyOutput,
confChan *chainntnfs.ConfirmationEvent) {
defer u.wg.Done()
select {
case txConfirmation, ok := <-confChan.Confirmed:
if !ok {
utxnLog.Errorf("Notification chan "+
"closed, can't advance baby output %v",
baby.OutPoint())
return
}
baby.SetConfHeight(txConfirmation.BlockHeight)
case <-u.quit:
return
}
u.mu.Lock()
defer u.mu.Unlock()
// TODO(conner): add retry logic?
err := u.cfg.Store.CribToKinder(baby)
if err != nil {
utxnLog.Errorf("Unable to move htlc output from "+
"crib to kindergarten bucket: %v", err)
return
}
utxnLog.Infof("Htlc output %v promoted to "+
"kindergarten", baby.OutPoint())
}
// registerPreschoolConf is responsible for subscribing to the confirmation of
// a commitment transaction, or an htlc success transaction for an incoming
// HTLC on our commitment transaction.. If successful, the provided preschool
// output will be moved persistently into the kindergarten state within the
// nursery store.
func (u *utxoNursery) registerPreschoolConf(kid *kidOutput, heightHint uint32) error {
txID := kid.OutPoint().Hash
// TODO(roasbeef): ensure we don't already have one waiting, need to
// de-duplicate
// * need to do above?
pkScript := kid.signDesc.Output.PkScript
confChan, err := u.cfg.Notifier.RegisterConfirmationsNtfn(
&txID, pkScript, u.cfg.ConfDepth, heightHint,
)
if err != nil {
return err
}
var outputType string
if kid.isHtlc {