-
Notifications
You must be signed in to change notification settings - Fork 149
Expand file tree
/
Copy pathaux_sweeper.go
More file actions
2752 lines (2369 loc) · 83 KB
/
Copy pathaux_sweeper.go
File metadata and controls
2752 lines (2369 loc) · 83 KB
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 tapchannel
import (
"bytes"
"context"
"fmt"
"math"
"net/url"
"slices"
"sync"
"sync/atomic"
"github.com/btcsuite/btcd/btcec/v2"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/lightninglabs/taproot-assets/address"
"github.com/lightninglabs/taproot-assets/asset"
"github.com/lightninglabs/taproot-assets/fn"
"github.com/lightninglabs/taproot-assets/proof"
"github.com/lightninglabs/taproot-assets/tapchannelmsg"
cmsg "github.com/lightninglabs/taproot-assets/tapchannelmsg"
"github.com/lightninglabs/taproot-assets/tapfreighter"
"github.com/lightninglabs/taproot-assets/tapgarden"
"github.com/lightninglabs/taproot-assets/tappsbt"
"github.com/lightninglabs/taproot-assets/tapscript"
"github.com/lightninglabs/taproot-assets/tapsend"
lfn "github.com/lightningnetwork/lnd/fn/v2"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/keychain"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwire"
"github.com/lightningnetwork/lnd/sweep"
"github.com/lightningnetwork/lnd/tlv"
"golang.org/x/exp/maps"
)
const (
// sweeperBudgetMultiplier is the multiplier used to determine the
// budget expressed in sats, report to lnd's sweeper. As we have small
// outputs on chain, we'll need an increased budget (the amount we
// should spend on fees) to make sure the outputs are always swept.
sweeperBudgetMultiplier = 20
)
// resolutionReq carries a request to resolve a contract output along with a
// response channel of the result.
type resolutionReq struct {
// req is the resolution request that we'll use to resolve the
// contract.
req lnwallet.ResolutionReq
// resp is the channel that we'll use to send the result of the
// resolution.
resp chan lfn.Result[tlv.Blob]
}
// sweepAddrReq is a request to sweep a set of inputs to a specified address.
type sweepAddrReq struct {
// inputs is the set of inputs to be swept.
inputs []input.Input
// change is the addr that the sweeper will use for the non-asset
// funds. This includes an internal key so we can generate an exclusion
// proof for the sweep transaction.
change lnwallet.AddrWithKey
// resp is the channel that we'll use to send the result of the sweep.
resp chan lfn.Result[sweep.SweepOutput]
}
// broadcastReq is used by the sweeper to notify us of a transaction broadcast.
type broadcastReq struct {
// req holds the sweep request that includes the set of inputs to be
// swept.
req *sweep.BumpRequest
// tx is the transaction to be broadcast.
tx *wire.MsgTx
// fee is the fee that was used for the transaction.
fee btcutil.Amount
// outpointToTxIndex maps a spent outpoint to the tx index on the sweep
// transaction of the corresponding output. This is only needed to make
// sure we make proofs properly for the pre-signed HTLC transactions.
outpointToTxIndex map[wire.OutPoint]int
// resp is the error result of the broadcast.
resp chan error
}
// AuxSweeperCfg holds the configuration for the AuxSweeper.
type AuxSweeperCfg struct {
// AddrBook is the address book that the signer will use to generate
// new script and internal keys for sweeping purposes.
AddrBook *address.Book
// ChainParams are the chain parameters of the network the signer is
// operating on.
ChainParams address.ChainParams
// Signer is the backing wallet that can sign virtual packets.
Signer VirtualPacketSigner
// TxSender is what we'll use to broadcast a transaction to the
// network, while ensuring we also update all our asset and UTXO state
// on disk (insert a proper transfer, etc., etc.).
TxSender tapfreighter.Porter
// DefaultCourierAddr is the default address the funding controller uses
// to deliver the funding output proofs to the channel peer.
DefaultCourierAddr *url.URL
// ProofFetcher is used to fetch proofs needed to properly import the
// funding output into the database as our own.
ProofFetcher proof.CourierDispatch
// ProofArchive is used to store import funding output proofs.
ProofArchive proof.Archiver
// HeaderVerifier is used to verify headers in a proof.
HeaderVerifier proof.HeaderVerifier
// GroupVerifier is used to verify group keys in a proof.
GroupVerifier proof.GroupVerifier
// ChainBridge is used to fetch blocks from the main chain.
ChainBridge tapgarden.ChainBridge
// IgnoreChecker is an optional function that can be used to check if
// a proof should be ignored.
IgnoreChecker lfn.Option[proof.IgnoreChecker]
}
// AuxSweeper is used to sweep funds from a commitment transaction that has
// been broadcast on chain (a force close). This subsystem interacts with the
// contract resolution and sweeping subsystems of lnd.
type AuxSweeper struct {
started atomic.Bool
stopped atomic.Bool
resolutionReqs chan *resolutionReq
sweepAddrReqs chan *sweepAddrReq
broadcastReqs chan *broadcastReq
cfg *AuxSweeperCfg
quit chan struct{}
wg sync.WaitGroup
}
// NewAuxSweeper creates a new instance of the AuxSweeper from the specified
// config.
func NewAuxSweeper(cfg *AuxSweeperCfg) *AuxSweeper {
return &AuxSweeper{
resolutionReqs: make(chan *resolutionReq),
sweepAddrReqs: make(chan *sweepAddrReq),
broadcastReqs: make(chan *broadcastReq),
cfg: cfg,
quit: make(chan struct{}),
}
}
// Start starts the AuxSweeper.
func (a *AuxSweeper) Start() error {
if !a.started.CompareAndSwap(false, true) {
return nil
}
log.Infof("Starting AuxSweeper")
a.wg.Add(1)
go a.contractResolver()
return nil
}
// Stop stops the AuxSweeper.
func (a *AuxSweeper) Stop() error {
if !a.stopped.CompareAndSwap(true, false) {
return nil
}
log.Infof("Stopping AuxSweeper")
close(a.quit)
a.wg.Wait()
return nil
}
// createSweepVpackets creates vPackets that sweep the funds from the specified
// set of asset inputs into the backing wallet.
func (a *AuxSweeper) createSweepVpackets(sweepInputs []*cmsg.AssetOutput,
tapscriptDesc lfn.Result[tapscriptSweepDesc],
resReq lnwallet.ResolutionReq) lfn.Result[[]*tappsbt.VPacket] {
type returnType = []*tappsbt.VPacket
log.Infof("Creating sweep packets for %v inputs", len(sweepInputs))
// Unpack the tapscript desc, as we need it to be able to continue
// forward.
sweepDesc, err := tapscriptDesc.Unpack()
if err != nil {
return lfn.Err[returnType](err)
}
allocs := make([]*tapsend.Allocation, 0, len(sweepInputs))
ctx := context.Background()
// If this is a second level HTLC sweep, then we already have
// the output information locked in, as this was a pre-signed
// transaction.
if sweepDesc.auxSigInfo.IsSome() {
var cltvTimeout fn.Option[uint32]
sweepDesc.absoluteDelay.WhenSome(func(delay uint64) {
cltvTimeout = fn.Some(uint32(delay))
})
htlcIndex := resReq.HtlcID.UnwrapOr(math.MaxUint64)
alloc, err := createSecondLevelHtlcAllocations(
resReq.ChanType, resReq.Initiator, sweepInputs,
resReq.HtlcAmt, resReq.CommitCsvDelay, *resReq.KeyRing,
fn.Some(resReq.ContractPoint.Index), cltvTimeout,
htlcIndex,
)
if err != nil {
return lfn.Err[returnType](err)
}
allocs = append(allocs, alloc...)
} else {
// Otherwise, for each out we want to sweep, we'll construct an
// allocation that we'll use to deliver the funds back to the
// wallet.
sweepAssetSum := tapchannelmsg.OutputSum(sweepInputs)
// For this local allocation we'll need to create a new script
// key to use for the sweep transaction.
scriptKeyGen := func(asset.ID) (asset.ScriptKey, error) {
var emptyKey asset.ScriptKey
scriptKey, err := a.cfg.AddrBook.NextScriptKey(
ctx, asset.TaprootAssetsKeyFamily,
)
if err != nil {
return emptyKey, err
}
return scriptKey, nil
}
// With the script key created, we can make a new allocation
// that will be used to sweep the funds back to our wallet.
//
// We leave out the internal key here, as we'll make it later
// once we actually have the other set of inputs we need to
// sweep.
allocs = append(allocs, &tapsend.Allocation{
Type: tapsend.CommitAllocationToLocal,
// We don't need to worry about sorting, as
// we'll always be the first output index in the
// transaction.
OutputIndex: 0,
Amount: sweepAssetSum,
AssetVersion: asset.V1,
BtcAmount: tapsend.DummyAmtSats,
GenScriptKey: scriptKeyGen,
})
}
log.Infof("Created %v allocations for commit tx sweep: %v",
len(allocs), limitSpewer.Sdump(allocs))
// With the allocations created above, we'll now extract a slice of
// each of the input proofs for each asset.
inputProofs := fn.Map(
sweepInputs, func(o *cmsg.AssetOutput) *proof.Proof {
return &o.Proof.Val
},
)
// With the proofs constructed, we can now distribute the coins to
// create the vPackets that we'll pass on to the next stage.
vPackets, err := tapsend.DistributeCoins(
inputProofs, allocs, &a.cfg.ChainParams, true, tappsbt.V1,
)
if err != nil {
return lfn.Errf[returnType]("error distributing coins: %w", err)
}
log.Infof("Created %v sweep packets: %v", len(vPackets),
limitSpewer.Sdump(vPackets))
// Next, we'll prepare all the vPackets for the sweep transaction, and
// also set the courier address.
courierAddr := a.cfg.DefaultCourierAddr
for idx := range vPackets {
// If we have a relative delay, then we'll set it for all the
// vOuts in this packet.
sweepDesc.relativeDelay.WhenSome(func(delay uint64) {
for _, vOut := range vPackets[idx].Outputs {
vOut.RelativeLockTime = delay
}
})
// Similarly, if we have an absolute delay, we'll set it for all
// the vOuts in this packet.
sweepDesc.absoluteDelay.WhenSome(func(expiry uint64) {
for _, vOut := range vPackets[idx].Outputs {
vOut.LockTime = expiry
}
})
err := tapsend.PrepareOutputAssets(ctx, vPackets[idx])
if err != nil {
return lfn.Errf[returnType]("unable to prepare output "+
"assets: %w", err)
}
for outIdx := range vPackets[idx].Outputs {
//nolint:lll
vPackets[idx].Outputs[outIdx].ProofDeliveryAddress = courierAddr
}
}
return lfn.Ok(vPackets)
}
// signSweepVpackets attempts to sign the vPackets specified using the passed
// sign desc and script tree.
func (a *AuxSweeper) signSweepVpackets(vPackets []*tappsbt.VPacket,
signDesc input.SignDescriptor, tapTweak, ctrlBlock []byte,
auxSigDesc lfn.Option[lnwallet.AuxSigDesc],
secondLevelSigIndex lfn.Option[uint32]) error {
// Before we sign below, we also need to generate the tapscript With
// the vPackets prepared, we can now sign the output asset we'll create
// at a later step.
for vPktIndex, vPacket := range vPackets {
if len(vPacket.Inputs) != 1 {
return fmt.Errorf("expected single input, got %v",
len(vPacket.Inputs))
}
// Each vPacket only has a single input, as we're sweeping a
// single asset from our commitment output.
vIn := vPacket.Inputs[0]
// Next, we'll apply the sign desc to the vIn, setting the PSBT
// specific fields. Along the way, we'll apply any relevant
// tweaks to generate the key we'll use to verify the
// signature.
signingKey, leafToSign := applySignDescToVIn(
signDesc, vIn, &a.cfg.ChainParams, tapTweak,
)
// In this case, the witness isn't special, so we'll set the
// control block now for it.
vIn.TaprootLeafScript[0].ControlBlock = ctrlBlock
log.Debugf("signing vPacket for input=%v",
limitSpewer.Sdump(vIn.PrevID))
// With everything set, we can now sign the new leaf we'll
// sweep into.
ctxb := context.Background()
signed, err := a.cfg.Signer.SignVirtualPacket(
ctxb, vPacket, tapfreighter.SkipInputProofVerify(),
tapfreighter.WithValidator(&schnorrSigValidator{
pubKey: signingKey,
tapLeaf: lfn.Some(leafToSign),
signMethod: input.TaprootScriptSpendSignMethod,
}),
)
if err != nil {
return fmt.Errorf("error signing virtual "+
"packet: %w", err)
}
if len(signed) != 1 || signed[0] != 0 {
return fmt.Errorf("error signing virtual packet, " +
"got no sig")
}
// At this point, the witness looks like: <sig> <witnessScript>
// <ctrlBlock>. This is a second level transaction, so we have
// another signature that we need to add to the witness this
// additional signature for the multi-sig.
err = lfn.MapOptionZ(
auxSigDesc,
func(aux lnwallet.AuxSigDesc) error {
assetSigs, err := cmsg.DecodeAssetSigListRecord(
aux.AuxSig,
)
if err != nil {
return fmt.Errorf("error "+
"decoding asset sig list "+
"record: %w", err)
}
auxSig := assetSigs.Sigs[vPktIndex]
// With the sig obtained, we'll now insert the
// signature at the specified index.
//nolint:lll
sigIndex, err := secondLevelSigIndex.UnwrapOrErr(
fmt.Errorf("no sig index"),
)
if err != nil {
return err
}
auxSigBytes := append(
auxSig.Sig.Val.RawBytes(),
byte(auxSig.SigHashType.Val),
)
newAsset := vPacket.Outputs[0].Asset
//nolint:lll
prevWitness := newAsset.PrevWitnesses[0].TxWitness
prevWitness = slices.Insert(
prevWitness, int(sigIndex), auxSigBytes,
)
return newAsset.UpdateTxWitness(0, prevWitness)
},
)
if err != nil {
return err
}
}
return nil
}
// vPktsWithInput couples a vPkt along with the input that contained it.
type vPktsWithInput struct {
// btcInput is the Bitcoin that the vPkt will the spending from (on the
// TAP layer).
btcInput input.Input
// vPkts is the set of vPacket that will be used to spend the input.
vPkts []*tappsbt.VPacket
// tapSigDesc houses the information we'll need to re-sign the vPackets
// above. Note that this is only set if this is a second level packet.
tapSigDesc lfn.Option[cmsg.TapscriptSigDesc]
}
// isPresigned returns true if the vPktsWithInput is presigned. This will be the
// for an HTLC spent directly from our local commitment transaction.
func (v vPktsWithInput) isPresigned() bool {
witType := v.btcInput.WitnessType()
switch witType {
case input.TaprootHtlcAcceptedLocalSuccess:
return true
case input.TaprootHtlcLocalOfferedTimeout:
return true
default:
return false
}
}
// sweepVpkts contains the set of vPkts needed for sweeping an output. Most
// outputs will only have the first level specified. The second level is needed
// for HTLC outputs on our local commitment transaction.
type sweepVpkts struct {
// firstLevel houses vPackets that are used to sweep outputs directly
// from the commitment transaction.
firstLevel []vPktsWithInput
// secondLevel is used to sweep outputs that are created by second level
// HTLC transactions.
secondLevel []vPktsWithInput
}
// firstLevelPkts returns a slice of the first level pkts.
func (s sweepVpkts) firstLevelPkts() []*tappsbt.VPacket {
return fn.FlatMap(
s.firstLevel, func(v vPktsWithInput) []*tappsbt.VPacket {
return v.vPkts
},
)
}
// secondLevelPkts returns a slice of the second level pkts.
func (s sweepVpkts) secondLevelPkts() []*tappsbt.VPacket {
return fn.FlatMap(
s.secondLevel, func(v vPktsWithInput) []*tappsbt.VPacket {
return v.vPkts
},
)
}
// allPkts returns a slice of both the first and second level pkts.
func (s sweepVpkts) allPkts() []*tappsbt.VPacket {
return append(s.firstLevelPkts(), s.secondLevelPkts()...)
}
// allVpktsWithInput returns a slice of all vPktsWithInput.
func (s sweepVpkts) allVpktsWithInput() []vPktsWithInput {
return append(s.firstLevel, s.secondLevel...)
}
// directSpendPkts returns the slice of all vPkts that are a direct spend from
// the commitment transaction. This excludes vPkts that are the pre-signed 2nd
// level transaction variant.
func (s sweepVpkts) directSpendPkts() []*tappsbt.VPacket {
directSpends := lfn.Filter(
s.allVpktsWithInput(), func(vi vPktsWithInput) bool {
return !vi.isPresigned()
},
)
directPkts := fn.FlatMap(
directSpends, func(v vPktsWithInput) []*tappsbt.VPacket {
return v.vPkts
},
)
return directPkts
}
// createAndSignSweepVpackets creates vPackets that sweep the funds from the
// channel to the wallet, and then signs them as well.
func (a *AuxSweeper) createAndSignSweepVpackets(
sweepInputs []*cmsg.AssetOutput, resReq lnwallet.ResolutionReq,
sweepDesc lfn.Result[tapscriptSweepDesc],
) lfn.Result[[]*tappsbt.VPacket] {
type returnType = []*tappsbt.VPacket
type resultType = lfn.Result[returnType]
// Based on the sweep inputs, make vPackets that sweep all the inputs
// into a new output with a fresh script key. They won't have an
// internal key set, we'll do that when we go to make the output to
// anchor them all. We'll then take those, then sign all the vPackets
// based on the specified sweepDesc.
signPkts := func(vPkts []*tappsbt.VPacket,
desc tapscriptSweepDesc) resultType {
// If this is a second level output, then we'll use the
// specified aux sign desc, otherwise, we'll use the
// normal one.
signDesc := lfn.MapOption(
func(aux lnwallet.AuxSigDesc) input.SignDescriptor {
return aux.SignDetails.SignDesc
},
)(desc.auxSigInfo).UnwrapOr(resReq.SignDesc)
err := a.signSweepVpackets(
vPkts, signDesc, desc.scriptTree.TapTweak(),
desc.ctrlBlockBytes, desc.auxSigInfo,
desc.secondLevelSigIndex,
)
if err != nil {
return lfn.Err[returnType](err)
}
return lfn.Ok(vPkts)
}
return lfn.FlatMapResult(
a.createSweepVpackets(sweepInputs, sweepDesc, resReq),
func(vPkts []*tappsbt.VPacket) resultType {
return lfn.FlatMapResult(
sweepDesc,
func(desc tapscriptSweepDesc) resultType {
return signPkts(vPkts, desc)
},
)
},
)
}
// tapscriptSweepDesc is a helper struct that contains the tapscript tree and
// the control block needed to generate a valid spend.
type tapscriptSweepDesc struct {
auxSigInfo lfn.Option[lnwallet.AuxSigDesc]
scriptTree input.TapscriptDescriptor
ctrlBlockBytes []byte
relativeDelay lfn.Option[uint64]
absoluteDelay lfn.Option[uint64]
secondLevelSigIndex lfn.Option[uint32]
}
// tapscriptSweepDescs contains the sweep decs for the first and second level.
// Most outputs only go to the first level, but HTLCs on our local commitment
// transaction go to the second level.
type tapscriptSweepDescs struct {
firstLevel tapscriptSweepDesc
secondLevel lfn.Option[tapscriptSweepDesc]
}
// commitNoDelaySweepDesc creates a sweep desc for a commitment output that
// resides on the remote party's commitment transaction. This output is a
// non-delay output, so we don't need to worry about the CSV delay when
// sweeping it.
func commitNoDelaySweepDesc(keyRing *lnwallet.CommitmentKeyRing,
csvDelay uint32) lfn.Result[tapscriptSweepDescs] {
type returnType = tapscriptSweepDescs
// We'll make the script tree for the to remote script (we're remote as
// this is their commitment transaction). We don't have an auxLeaf here
// as we're on the TAP layer.
toRemoteScriptTree, err := input.NewRemoteCommitScriptTree(
keyRing.ToRemoteKey, input.NoneTapLeaf(),
)
if err != nil {
return lfn.Errf[returnType]("unable to make remote "+
"script tree: %w", err)
}
// Now that we have the script tree, we'll make the control block
// needed to spend it.
ctrlBlock, err := toRemoteScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[returnType](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Errf[returnType]("unable to encode ctrl "+
"block: %w", err)
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
scriptTree: toRemoteScriptTree,
relativeDelay: lfn.Some(uint64(csvDelay)),
ctrlBlockBytes: ctrlBlockBytes,
},
})
}
// commitDelaySweepDesc creates a sweep desc for a commitment output that
// resides on our local commitment transaction. This output is a delay output,
// so we need to mind the CSV delay when sweeping it.
func commitDelaySweepDesc(keyRing *lnwallet.CommitmentKeyRing,
csvDelay uint32) lfn.Result[tapscriptSweepDescs] {
type returnType = tapscriptSweepDescs
// We'll make the script tree for the to remote script (we're remote as
// this is their commitment transaction). We don't have an auxLeaf here
// as we're on the TAP layer.
toLocalScriptTree, err := input.NewLocalCommitScriptTree(
csvDelay, keyRing.ToLocalKey, keyRing.RevocationKey,
input.NoneTapLeaf(),
)
if err != nil {
return lfn.Err[returnType](err)
}
// Now that we have the script tree, we'll make the control block
// needed to spend it.
ctrlBlock, err := toLocalScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[returnType](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[returnType](err)
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
scriptTree: toLocalScriptTree,
relativeDelay: lfn.Some(uint64(csvDelay)),
ctrlBlockBytes: ctrlBlockBytes,
},
})
}
// commitRevokeSweepDesc creates a sweep desc for a commitment output that is
// the local output on the remote party's commitment transaction. We can seep
// this in the case of a revoked commitment.
func commitRevokeSweepDesc(keyRing *lnwallet.CommitmentKeyRing,
csvDelay uint32) lfn.Result[tapscriptSweepDescs] {
type returnType = tapscriptSweepDescs
// To sweep their revoked output, we'll make the script tree for the
// local tree of their commitment transaction, which is actually their
// output.
toLocalScriptTree, err := input.NewLocalCommitScriptTree(
csvDelay, keyRing.ToLocalKey, keyRing.RevocationKey,
input.NoneTapLeaf(),
)
if err != nil {
return lfn.Err[returnType](err)
}
// Now that we have the script tree, we'll make the control block
// needed to spend it, but taking the revoked path.
ctrlBlock, err := toLocalScriptTree.CtrlBlockForPath(
input.ScriptPathRevocation,
)
if err != nil {
return lfn.Err[returnType](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
scriptTree: toLocalScriptTree,
ctrlBlockBytes: ctrlBlockBytes,
},
})
}
// remoteHtlcTimeoutSweepDesc creates a sweep desc for an HTLC output that is
// close to timing out on the remote party's commitment transaction.
func remoteHtlcTimeoutSweepDesc(originalKeyRing *lnwallet.CommitmentKeyRing,
payHash []byte, csvDelay uint32, htlcExpiry uint32,
index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] {
// We're sweeping an HTLC output, which has a tweaked script key. To be
// able to create the correct control block, we need to tweak the key
// ring with the index of the HTLC.
tweakedKeyRing := TweakedRevocationKeyRing(originalKeyRing, index)
// We're sweeping a timed out HTLC, which means that we'll need to
// create the receiver's HTLC script tree (from the remote party's PoV).
htlcScriptTree, err := input.ReceiverHTLCScriptTaproot(
htlcExpiry, tweakedKeyRing.LocalHtlcKey,
tweakedKeyRing.RemoteHtlcKey, tweakedKeyRing.RevocationKey,
payHash, lntypes.Remote, input.NoneTapLeaf(),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// Now that we have the script tree, we'll make the control block needed
// to spend it, but taking the revoked path.
ctrlBlock, err := htlcScriptTree.CtrlBlockForPath(
input.ScriptPathTimeout,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
relativeDelay: lfn.Some(uint64(csvDelay)),
absoluteDelay: lfn.Some(uint64(htlcExpiry)),
scriptTree: htlcScriptTree,
ctrlBlockBytes: ctrlBlockBytes,
},
})
}
// remoteHtlcSuccessSweepDesc creates a sweep desc for an HTLC output present on
// the remote party's commitment transaction that we can sweep with the
// preimage.
func remoteHtlcSuccessSweepDesc(originalKeyRing *lnwallet.CommitmentKeyRing,
payHash []byte, csvDelay uint32,
index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] {
// We're sweeping an HTLC output, which has a tweaked script key. To be
// able to create the correct control block, we need to tweak the key
// ring with the index of the HTLC.
tweakedKeyRing := TweakedRevocationKeyRing(originalKeyRing, index)
// We're planning on sweeping an HTLC that we know the preimage to,
// which the remote party sent, so we'll construct the sender version of
// the HTLC script tree (from their PoV, they're the sender).
htlcScriptTree, err := input.SenderHTLCScriptTaproot(
tweakedKeyRing.RemoteHtlcKey, tweakedKeyRing.LocalHtlcKey,
tweakedKeyRing.RevocationKey, payHash, lntypes.Remote,
input.NoneTapLeaf(),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// Now that we have the script tree, we'll make the control block needed
// to spend it, but taking the revoked path.
ctrlBlock, err := htlcScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
relativeDelay: lfn.Some(uint64(csvDelay)),
ctrlBlockBytes: ctrlBlockBytes,
scriptTree: htlcScriptTree,
},
})
}
// localHtlcTimeoutSweepDesc creates a sweep desc for an HTLC output that is
// present on our local commitment transaction. These are second level HTLCs, so
// we'll need to perform two stages of sweeps.
func localHtlcTimeoutSweepDesc(req lnwallet.ResolutionReq,
index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] {
const isIncoming = false
payHash, err := req.PayHash.UnwrapOrErr(
fmt.Errorf("no pay hash"),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
htlcExpiry, err := req.CltvDelay.UnwrapOrErr(
fmt.Errorf("no htlc expiry"),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// We're sweeping an HTLC output, which has a tweaked script key. To be
// able to create the correct control block, we need to tweak the key
// ring with the index of the HTLC.
tweakedKeyRing := TweakedRevocationKeyRing(req.KeyRing, index)
// We'll need to complete the control block to spend the second-level
// HTLC, so first we'll make the script tree for the HTLC.
htlcScriptTree, err := lnwallet.GenTaprootHtlcScript(
isIncoming, lntypes.Local, htlcExpiry, payHash, tweakedKeyRing,
lfn.None[txscript.TapLeaf](),
)
if err != nil {
return lfn.Errf[tapscriptSweepDescs]("error creating "+
"HTLC script: %w", err)
}
// Now that we have the script tree, we'll make the control block needed
// to spend it, but taking the timeout path.
ctrlBlock, err := htlcScriptTree.CtrlBlockForPath(
input.ScriptPathTimeout,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// For the second level transaction, the witness looks like this:
//
// <receiver sig> <sender sig> <timeout_script> <control_block>
//
// We're the sender, so we'll need to insert their sig at the very
// front.
sigIndex := lfn.Some(uint32(0))
// As this is an HTLC on our local commitment transaction, we'll also
// need to generate a sweep desc for second level HTLC.
secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree(
tweakedKeyRing.RevocationKey, req.KeyRing.ToLocalKey,
req.CommitCsvDelay, lfn.None[txscript.TapLeaf](),
)
if err != nil {
return lfn.Errf[tapscriptSweepDescs]("error "+
"creating second level htlc script: %w", err)
}
secondLevelCtrBlock, err := secondLevelScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
secondLevelCtrlBlockBytes, err := secondLevelCtrBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
secondLevelDesc := tapscriptSweepDesc{
scriptTree: secondLevelScriptTree,
relativeDelay: lfn.Some(uint64(req.CommitCsvDelay)),
ctrlBlockBytes: secondLevelCtrlBlockBytes,
}
return lfn.Ok(tapscriptSweepDescs{
firstLevel: tapscriptSweepDesc{
scriptTree: htlcScriptTree,
ctrlBlockBytes: ctrlBlockBytes,
relativeDelay: lfn.Some(uint64(req.CsvDelay)),
absoluteDelay: lfn.Some(uint64(htlcExpiry)),
auxSigInfo: req.AuxSigDesc,
secondLevelSigIndex: sigIndex,
},
secondLevel: lfn.Some(secondLevelDesc),
})
}
// localHtlcSuccessSweepDesc creates a sweep desc for an HTLC output that is
// present on our local commitment transaction that we can sweep with a
// preimage. These sweeps take two stages, so we'll add that extra information.
func localHtlcSuccessSweepDesc(req lnwallet.ResolutionReq,
index input.HtlcIndex) lfn.Result[tapscriptSweepDescs] {
const isIncoming = true
payHash, err := req.PayHash.UnwrapOrErr(
fmt.Errorf("no pay hash"),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
htlcExpiry, err := req.CltvDelay.UnwrapOrErr(
fmt.Errorf("no htlc expiry"),
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// We're sweeping an HTLC output, which has a tweaked script key. To be
// able to create the correct control block, we need to tweak the key
// ring with the index of the HTLC.
tweakedKeyRing := TweakedRevocationKeyRing(req.KeyRing, index)
// We'll need to complete the control block to spend the second-level
// HTLC, so first we'll make the script tree for the HTLC.
htlcScriptTree, err := lnwallet.GenTaprootHtlcScript(
isIncoming, lntypes.Local, htlcExpiry, payHash, tweakedKeyRing,
lfn.None[txscript.TapLeaf](),
)
if err != nil {
return lfn.Errf[tapscriptSweepDescs]("error creating "+
"HTLC script: %w", err)
}
// Now that we have the script tree, we'll make the control block needed
// to spend it, but taking the success path.
ctrlBlock, err := htlcScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
ctrlBlockBytes, err := ctrlBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
// For the second level transaction, the witness looks like this:
//
// * <sender sig> <receiver sig> <preimage> <success_script>
// <control_block>
//
// In this case, we're the receiver. After we sign the witness will look
// like this: <receiver sig> <witness script> <ctrlBlock>.
//
// So we'll need to insert the remote party's signature at the very
// front.
sigIndex := lfn.Some(uint32(0))
// As this is an HTLC on our local commitment transaction, we'll also
// need to generate a sweep desc for second level HTLC.
secondLevelScriptTree, err := input.TaprootSecondLevelScriptTree(
tweakedKeyRing.RevocationKey, req.KeyRing.ToLocalKey,
req.CommitCsvDelay, lfn.None[txscript.TapLeaf](),
)
if err != nil {
return lfn.Errf[tapscriptSweepDescs]("error "+
"creating second level htlc script: %w", err)
}
secondLevelCtrBlock, err := secondLevelScriptTree.CtrlBlockForPath(
input.ScriptPathSuccess,
)
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
secondLevelCtrlBlockBytes, err := secondLevelCtrBlock.ToBytes()
if err != nil {
return lfn.Err[tapscriptSweepDescs](err)
}
secondLevelDesc := tapscriptSweepDesc{