-
Notifications
You must be signed in to change notification settings - Fork 133
Expand file tree
/
Copy pathmanager.go
More file actions
1154 lines (965 loc) · 31.3 KB
/
Copy pathmanager.go
File metadata and controls
1154 lines (965 loc) · 31.3 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 withdraw
import (
"context"
"errors"
"fmt"
"reflect"
"strings"
"sync"
"sync/atomic"
"github.com/btcsuite/btcd/btcec/v2/schnorr"
"github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
"github.com/btcsuite/btcd/btcutil"
"github.com/btcsuite/btcd/chaincfg"
"github.com/btcsuite/btcd/chaincfg/chainhash"
"github.com/btcsuite/btcd/txscript"
"github.com/btcsuite/btcd/wire"
"github.com/btcsuite/btcwallet/chain"
"github.com/lightninglabs/lndclient"
"github.com/lightninglabs/loop/staticaddr/deposit"
staticaddressrpc "github.com/lightninglabs/loop/swapserverrpc"
"github.com/lightningnetwork/lnd/chainntnfs"
"github.com/lightningnetwork/lnd/input"
"github.com/lightningnetwork/lnd/lnrpc/walletrpc"
"github.com/lightningnetwork/lnd/lntypes"
"github.com/lightningnetwork/lnd/lnwallet"
"github.com/lightningnetwork/lnd/lnwallet/chainfee"
"golang.org/x/sync/errgroup"
)
var (
// ErrWithdrawingMixedDeposits is returned when a withdrawal is
// requested for deposits in different states.
ErrWithdrawingMixedDeposits = errors.New("need to withdraw deposits " +
"having the same state, either all deposited or all " +
"withdrawing")
// ErrDiffPreviousWithdrawalTx signals that the user selected new
// deposits that have different previous withdrawal transactions.
ErrDiffPreviousWithdrawalTx = errors.New("can't bump fee for " +
"deposits with different previous withdrawal tx hash")
// ErrMissingPreviousWithdrawn is returned when the user tries to bump
// the fee for a subset of previously selected deposits to withdraw.
ErrMissingPreviousWithdrawn = errors.New("can't bump fee for subset " +
"of clustered deposits")
// MinConfs is the minimum number of confirmations we require for a
// deposit to be considered withdrawn.
MinConfs int32 = 3
// Is the default confirmation target for the fee estimation of the
// withdrawal transaction.
defaultConfTarget int32 = 3
)
// ManagerConfig holds the configuration for the address manager.
type ManagerConfig struct {
// StaticAddressServerClient is the client that calls the swap server
// rpcs to negotiate static address withdrawals.
StaticAddressServerClient staticaddressrpc.StaticAddressServerClient
// AddressManager gives the withdrawal manager access to static address
// parameters.
AddressManager AddressManager
// DepositManager gives the withdrawal manager access to the deposits
// enabling it to create and manage withdrawals.
DepositManager DepositManager
// WalletKit is the wallet client that is used to derive new keys from
// lnd's wallet.
WalletKit lndclient.WalletKitClient
// ChainParams is the chain configuration(mainnet, testnet...) this
// manager uses.
ChainParams *chaincfg.Params
// ChainNotifier is the chain notifier that is used to listen for new
// blocks.
ChainNotifier lndclient.ChainNotifierClient
// Signer is the signer client that is used to sign transactions.
Signer lndclient.SignerClient
// Store is the store that is used to persist the finalized withdrawal
// transactions.
Store *SqlStore
}
// newWithdrawalRequest is used to send withdrawal request to the manager main
// loop.
type newWithdrawalRequest struct {
outpoints []wire.OutPoint
respChan chan *newWithdrawalResponse
destAddr string
satPerVbyte int64
amount int64
}
// newWithdrawalResponse is used to return withdrawal info and error to the
// server.
type newWithdrawalResponse struct {
txHash string
withdrawalAddress string
err error
}
// Manager manages the withdrawal state machines.
type Manager struct {
cfg *ManagerConfig
// mu protects access to finalizedWithdrawalTxns.
mu sync.Mutex
// newWithdrawalRequestChan receives a list of outpoints that should be
// withdrawn. The request is forwarded to the managers main loop.
newWithdrawalRequestChan chan newWithdrawalRequest
// exitChan signals subroutines that the withdrawal manager is exiting.
exitChan chan struct{}
// errChan forwards errors from the withdrawal manager to the server.
errChan chan error
// initiationHeight stores the currently best known block height.
initiationHeight atomic.Uint32
// finalizedWithdrawalTx are the finalized withdrawal transactions that
// are published to the network and re-published on block arrivals.
finalizedWithdrawalTxns map[chainhash.Hash]*wire.MsgTx
}
// NewManager creates a new deposit withdrawal manager.
func NewManager(cfg *ManagerConfig, currentHeight uint32) *Manager {
m := &Manager{
cfg: cfg,
finalizedWithdrawalTxns: make(map[chainhash.Hash]*wire.MsgTx),
exitChan: make(chan struct{}),
newWithdrawalRequestChan: make(chan newWithdrawalRequest),
errChan: make(chan error),
}
m.initiationHeight.Store(currentHeight)
return m
}
// Run runs the deposit withdrawal manager.
func (m *Manager) Run(ctx context.Context, initChan chan struct{}) error {
newBlockChan, newBlockErrChan, err :=
m.cfg.ChainNotifier.RegisterBlockEpochNtfn(ctx)
if err != nil {
return err
}
err = m.recoverWithdrawals(ctx)
if err != nil {
return err
}
// Communicate to the caller that the address manager has completed its
// initialization.
close(initChan)
for {
select {
case <-newBlockChan:
err = m.republishWithdrawals(ctx)
if err != nil {
log.Errorf("Error republishing withdrawals: %v",
err)
}
case req := <-m.newWithdrawalRequestChan:
txHash, withdrawalAddress, err := m.WithdrawDeposits(
ctx, req.outpoints, req.destAddr,
req.satPerVbyte, req.amount,
)
if err != nil {
log.Errorf("Error withdrawing deposits: %v",
err)
}
// We forward the initialized loop-in and error to
// DeliverLoopInRequest.
resp := &newWithdrawalResponse{
txHash: txHash,
withdrawalAddress: withdrawalAddress,
err: err,
}
select {
case req.respChan <- resp:
case <-ctx.Done():
// Notify subroutines that the main loop has
// been canceled.
close(m.exitChan)
return ctx.Err()
}
case err = <-newBlockErrChan:
return err
case <-ctx.Done():
// Signal subroutines that the manager is exiting.
close(m.exitChan)
return ctx.Err()
}
}
}
func (m *Manager) recoverWithdrawals(ctx context.Context) error {
// To recover withdrawals we cluster those with equal withdrawal
// addresses and publish their withdrawal tx. Each cluster represents a
// separate withdrawal intent by the user.
withdrawingDeposits, err := m.cfg.DepositManager.GetActiveDepositsInState(
deposit.Withdrawing,
)
if err != nil {
return err
}
// Group the deposits by their finalized withdrawal transaction.
depositsByWithdrawalTx := make(map[chainhash.Hash][]*deposit.Deposit)
hash2tx := make(map[chainhash.Hash]*wire.MsgTx)
for _, d := range withdrawingDeposits {
withdrawalTx := d.FinalizedWithdrawalTx
if withdrawalTx == nil {
continue
}
txid := withdrawalTx.TxHash()
hash2tx[txid] = withdrawalTx
depositsByWithdrawalTx[txid] = append(
depositsByWithdrawalTx[txid], d,
)
}
// Publishing a transaction can take a while in neutrino mode, so
// do it in parallel.
eg := &errgroup.Group{}
// We can now reinstate each cluster of deposits for a withdrawal.
for txid, deposits := range depositsByWithdrawalTx {
eg.Go(func() error {
err := m.cfg.DepositManager.TransitionDeposits(
ctx, deposits, deposit.OnWithdrawInitiated,
deposit.Withdrawing,
)
if err != nil {
return err
}
tx, ok := hash2tx[txid]
if !ok {
return fmt.Errorf("can't find tx %v", txid)
}
_, err = m.publishFinalizedWithdrawalTx(ctx, tx)
if err != nil {
return err
}
err = m.handleWithdrawal(
ctx, deposits, tx.TxHash(),
tx.TxOut[0].PkScript,
)
if err != nil {
return err
}
m.mu.Lock()
m.finalizedWithdrawalTxns[tx.TxHash()] = tx
m.mu.Unlock()
return nil
})
}
// Wait for all goroutines to report back.
if err := eg.Wait(); err != nil {
return fmt.Errorf("error recovering withdrawals: %w", err)
}
return nil
}
// WithdrawDeposits starts a deposits withdrawal flow. If the amount is set to 0
// the full amount of the selected deposits will be withdrawn.
func (m *Manager) WithdrawDeposits(ctx context.Context,
outpoints []wire.OutPoint, destAddr string, satPerVbyte int64,
amount int64) (string, string, error) {
if len(outpoints) == 0 {
return "", "", fmt.Errorf("no outpoints selected to " +
"withdraw, unconfirmed deposits can't be withdrawn")
}
var (
deposits []*deposit.Deposit
allDeposited bool
allWithdrawing bool
)
// Ensure that the deposits are in a state in which they can be
// withdrawn.
deposits, allDeposited = m.cfg.DepositManager.AllOutpointsActiveDeposits(
outpoints, deposit.Deposited,
)
// If not all passed outpoints are in state Deposited, we'll check if
// they are all in state Withdrawing. If they are, then the user is
// requesting a fee bump, if not we'll return an error as we only allow
// fee bumping deposits in state Withdrawing.
if !allDeposited {
deposits, allWithdrawing = m.cfg.DepositManager.AllOutpointsActiveDeposits(
outpoints, deposit.Withdrawing,
)
if !allWithdrawing {
return "", "", ErrWithdrawingMixedDeposits
}
// If republishing of an existing withdrawal is requested we
// ensure that all deposits remain clustered in the context of
// the same withdrawal tx. We do this by checking that they have
// the same previous withdrawal tx hash. This ensures that the
// shape of the transaction stays the same.
prevWithdrawalTx := deposits[0].FinalizedWithdrawalTx
hash := prevWithdrawalTx.TxHash()
for i := 1; i < len(deposits); i++ {
if deposits[i].FinalizedWithdrawalTx.TxHash() != hash {
return "", "", ErrDiffPreviousWithdrawalTx
}
}
// We also avoid that the user selects a subset of previously
// clustered deposits for a fee bump. This would result in a
// different transaction shape.
outpointMap := make(map[wire.OutPoint]struct{})
for _, d := range deposits {
outpointMap[d.OutPoint] = struct{}{}
}
// Check that all previously withdrawn deposits are included in
// the new withdrawal.
for _, in := range prevWithdrawalTx.TxIn {
if _, ok := outpointMap[in.PreviousOutPoint]; !ok {
return "", "", ErrMissingPreviousWithdrawn
}
}
if len(deposits) != len(prevWithdrawalTx.TxIn) {
return "", "", ErrMissingPreviousWithdrawn
}
}
var (
withdrawalAddress btcutil.Address
err error
)
// Check if the user provided an address to withdraw to. If not, we'll
// generate a new address for them.
if destAddr != "" {
withdrawalAddress, err = btcutil.DecodeAddress(
destAddr, m.cfg.ChainParams,
)
if err != nil {
return "", "", err
}
} else {
withdrawalAddress, err = m.cfg.WalletKit.NextAddr(
ctx, lnwallet.DefaultAccountName,
walletrpc.AddressType_TAPROOT_PUBKEY, false,
)
if err != nil {
return "", "", err
}
}
finalizedTx, err := m.createFinalizedWithdrawalTx(
ctx, deposits, withdrawalAddress, satPerVbyte, amount,
)
if err != nil {
return "", "", err
}
published, err := m.publishFinalizedWithdrawalTx(ctx, finalizedTx)
if err != nil {
return "", "", err
}
if !published {
return "", "", nil
}
withdrawalPkScript, err := txscript.PayToAddrScript(withdrawalAddress)
if err != nil {
return "", "", fmt.Errorf("could not get withdrawal "+
"pkscript: %w", err)
}
// If this is the first time this cluster of deposits is withdrawn, we
// start a goroutine that listens for the spent of the first input of
// the withdrawal transaction.
// Since we ensure above that the same ensemble of deposits is
// republished in case of a fee bump, it suffices if only one spent
// notifier is run.
if allDeposited {
// Persist info about the finalized withdrawal.
err = m.cfg.Store.CreateWithdrawal(ctx, deposits)
if err != nil {
log.Errorf("Error persisting "+
"withdrawal: %v", err)
}
err = m.handleWithdrawal(
ctx, deposits, finalizedTx.TxHash(), withdrawalPkScript,
)
if err != nil {
return "", "", err
}
}
// If a previous withdrawal existed across the selected deposits, and
// it isn't the same as the new withdrawal, we remove it from the
// finalized withdrawals to stop republishing it on block arrivals.
deposits[0].Lock()
prevTx := deposits[0].FinalizedWithdrawalTx
deposits[0].Unlock()
if prevTx != nil && prevTx.TxHash() != finalizedTx.TxHash() {
m.mu.Lock()
delete(m.finalizedWithdrawalTxns, prevTx.TxHash())
m.mu.Unlock()
}
// Attach the finalized withdrawal tx to the deposits. After a client
// restart we can use this address as an indicator to republish the
// withdrawal tx and continue the withdrawal.
// Deposits with the same withdrawal tx are part of the same withdrawal.
for _, d := range deposits {
d.Lock()
d.FinalizedWithdrawalTx = finalizedTx
d.Unlock()
}
// Add the new withdrawal tx to the finalized withdrawals to republish
// it on block arrivals.
m.mu.Lock()
m.finalizedWithdrawalTxns[finalizedTx.TxHash()] = finalizedTx
m.mu.Unlock()
// Transition the deposits to the withdrawing state. If the user fee
// bumped a withdrawal this results in a NOOP transition.
err = m.cfg.DepositManager.TransitionDeposits(
ctx, deposits, deposit.OnWithdrawInitiated, deposit.Withdrawing,
)
if err != nil {
return "", "", fmt.Errorf("failed to transition deposits %w",
err)
}
// Update the deposits in the database.
for _, d := range deposits {
err = m.cfg.DepositManager.UpdateDeposit(ctx, d)
if err != nil {
return "", "", fmt.Errorf("failed to update "+
"deposit %w", err)
}
}
return finalizedTx.TxID(), withdrawalAddress.String(), nil
}
func (m *Manager) createFinalizedWithdrawalTx(ctx context.Context,
deposits []*deposit.Deposit, withdrawalAddress btcutil.Address,
satPerVbyte int64, selectedWithdrawalAmount int64) (*wire.MsgTx,
error) {
// Create a musig2 session for each deposit.
withdrawalSessions, clientNonces, err := m.createMusig2Sessions(
ctx, deposits,
)
if err != nil {
return nil, err
}
var withdrawalSweepFeeRate chainfee.SatPerKWeight
if satPerVbyte == 0 {
// Get the fee rate for the withdrawal sweep.
withdrawalSweepFeeRate, err = m.cfg.WalletKit.EstimateFeeRate(
ctx, defaultConfTarget,
)
if err != nil {
return nil, err
}
} else {
withdrawalSweepFeeRate = chainfee.SatPerKVByte(
satPerVbyte * 1000,
).FeePerKWeight()
}
params, err := m.cfg.AddressManager.GetStaticAddressParameters(ctx)
if err != nil {
return nil, fmt.Errorf("couldn't get confirmation height for "+
"deposit, %w", err)
}
outpoints := toOutpoints(deposits)
prevOuts := m.toPrevOuts(deposits, params.PkScript)
withdrawalTx, withdrawAmount, changeAmount, err := m.createWithdrawalTx(
ctx, outpoints, prevOuts,
btcutil.Amount(selectedWithdrawalAmount), withdrawalAddress,
withdrawalSweepFeeRate,
)
if err != nil {
return nil, err
}
// Request the server to sign the withdrawal transaction.
//
// The withdrawal and change amount are sent to the server with the
// expectation that the server just signs the transaction, without
// performing fee calculations and dust considerations. The client is
// responsible for that.
resp, err := m.cfg.StaticAddressServerClient.ServerWithdrawDeposits(
ctx, &staticaddressrpc.ServerWithdrawRequest{
Outpoints: toPrevoutInfo(outpoints),
ClientNonces: clientNonces,
ClientSweepAddr: withdrawalAddress.String(),
TxFeeRate: uint64(withdrawalSweepFeeRate),
WithdrawAmount: int64(withdrawAmount),
ChangeAmount: int64(changeAmount),
},
)
if err != nil {
return nil, err
}
coopServerNonces, err := toNonces(resp.ServerNonces)
if err != nil {
return nil, err
}
// Next we'll get our sweep tx signatures.
prevOutFetcher := txscript.NewMultiPrevOutFetcher(prevOuts)
_, err = m.signMusig2Tx(
ctx, prevOutFetcher, outpoints, m.cfg.Signer, withdrawalTx,
withdrawalSessions, coopServerNonces,
)
if err != nil {
return nil, err
}
// Now we'll finalize the sweepless sweep transaction.
finalizedTx, err := m.finalizeMusig2Transaction(
ctx, outpoints, m.cfg.Signer, withdrawalSessions,
withdrawalTx, resp.Musig2SweepSigs,
)
if err != nil {
return nil, err
}
return finalizedTx, nil
}
func (m *Manager) publishFinalizedWithdrawalTx(ctx context.Context,
tx *wire.MsgTx) (bool, error) {
if tx == nil {
return false, errors.New("can't publish, finalized " +
"withdrawal tx is nil")
}
log.Debugf("Publishing deposit withdrawal with txid: %v ...",
tx.TxHash())
txLabel := fmt.Sprintf("deposit-withdrawal-%v", tx.TxHash())
// Publish the withdrawal sweep transaction.
err := m.cfg.WalletKit.PublishTransaction(ctx, tx, txLabel)
if err != nil {
if !strings.Contains(err.Error(), chain.ErrSameNonWitnessData.Error()) &&
!strings.Contains(err.Error(), "output already spent") &&
!strings.Contains(err.Error(), chain.ErrInsufficientFee.Error()) {
return false, err
} else {
if strings.Contains(err.Error(), "output already spent") {
log.Warnf("output already spent, tx %v, %v",
tx.TxHash(), err)
}
return false, nil
}
} else {
log.Debugf("Published deposit withdrawal with txid: %v",
tx.TxHash())
}
return true, nil
}
// handleWithdrawal starts a goroutine that listens for the spent of the first
// input of the withdrawal transaction.
func (m *Manager) handleWithdrawal(ctx context.Context,
deposits []*deposit.Deposit, txHash chainhash.Hash,
withdrawalPkscript []byte) error {
addrParams, err := m.cfg.AddressManager.GetStaticAddressParameters(ctx)
if err != nil {
log.Errorf("error retrieving address params %w", err)
return fmt.Errorf("withdrawal failed")
}
d := deposits[0]
spentChan, errChan, err := m.cfg.ChainNotifier.RegisterSpendNtfn(
ctx, &d.OutPoint, addrParams.PkScript,
int32(d.ConfirmationHeight),
)
go func() {
select {
case spentTx := <-spentChan:
spendingHeight := uint32(spentTx.SpendingHeight)
// If the transaction received one confirmation, we
// ensure re-org safety by waiting for some more
// confirmations.
var confChan chan *chainntnfs.TxConfirmation
confChan, errChan, err =
m.cfg.ChainNotifier.RegisterConfirmationsNtfn(
ctx, spentTx.SpenderTxHash,
withdrawalPkscript, MinConfs,
int32(m.initiationHeight.Load()),
)
select {
case tx := <-confChan:
err = m.cfg.DepositManager.TransitionDeposits(
ctx, deposits, deposit.OnWithdrawn,
deposit.Withdrawn,
)
if err != nil {
log.Errorf("Error transitioning "+
"deposits: %v", err)
}
// Remove the withdrawal tx from the active
// withdrawals to stop republishing it on block
// arrivals.
m.mu.Lock()
delete(m.finalizedWithdrawalTxns, txHash)
m.mu.Unlock()
// Persist info about the finalized withdrawal.
err = m.cfg.Store.UpdateWithdrawal(
ctx, deposits, tx.Tx, spendingHeight,
addrParams.PkScript,
)
if err != nil {
log.Errorf("Error persisting "+
"withdrawal: %v", err)
}
case err := <-errChan:
log.Errorf("Error waiting for confirmation: %v",
err)
case <-ctx.Done():
log.Errorf("Withdrawal tx confirmation wait " +
"canceled")
}
case err := <-errChan:
log.Errorf("Error waiting for confirmation: %v", err)
case <-ctx.Done():
log.Errorf("Withdrawal tx confirmation wait canceled")
}
}()
return nil
}
func toOutpoints(deposits []*deposit.Deposit) []wire.OutPoint {
outpoints := make([]wire.OutPoint, len(deposits))
for i, d := range deposits {
outpoints[i] = wire.OutPoint{
Hash: d.Hash,
Index: d.Index,
}
}
return outpoints
}
// signMusig2Tx adds the server nonces to the musig2 sessions and signs the
// transaction.
func (m *Manager) signMusig2Tx(ctx context.Context,
prevOutFetcher *txscript.MultiPrevOutFetcher, outpoints []wire.OutPoint,
signer lndclient.SignerClient, tx *wire.MsgTx,
musig2sessions []*input.MuSig2SessionInfo,
counterPartyNonces [][musig2.PubNonceSize]byte) ([][]byte, error) {
sigHashes := txscript.NewTxSigHashes(tx, prevOutFetcher)
sigs := make([][]byte, len(outpoints))
for idx, outpoint := range outpoints {
if !reflect.DeepEqual(tx.TxIn[idx].PreviousOutPoint,
outpoint) {
return nil, fmt.Errorf("tx input does not match " +
"deposits")
}
taprootSigHash, err := txscript.CalcTaprootSignatureHash(
sigHashes, txscript.SigHashDefault, tx, idx,
prevOutFetcher,
)
if err != nil {
return nil, err
}
var digest [32]byte
copy(digest[:], taprootSigHash)
// Register the server's nonce before attempting to create our
// partial signature.
haveAllNonces, err := signer.MuSig2RegisterNonces(
ctx, musig2sessions[idx].SessionID,
[][musig2.PubNonceSize]byte{counterPartyNonces[idx]},
)
if err != nil {
return nil, err
}
// Sanity check that we have all the nonces.
if !haveAllNonces {
return nil, fmt.Errorf("invalid MuSig2 session: " +
"nonces missing")
}
// Since our MuSig2 session has all nonces, we can now create
// the local partial signature by signing the sig hash.
sig, err := signer.MuSig2Sign(
ctx, musig2sessions[idx].SessionID, digest, false,
)
if err != nil {
return nil, err
}
sigs[idx] = sig
}
return sigs, nil
}
func withdrawalValue(prevOuts map[wire.OutPoint]*wire.TxOut) btcutil.Amount {
var totalValue btcutil.Amount
for _, prevOut := range prevOuts {
totalValue += btcutil.Amount(prevOut.Value)
}
return totalValue
}
// toNonces converts a byte slice to a 66 byte slice.
func toNonces(nonces [][]byte) ([][musig2.PubNonceSize]byte, error) {
res := make([][musig2.PubNonceSize]byte, 0, len(nonces))
for _, n := range nonces {
nonce, err := byteSliceTo66ByteSlice(n)
if err != nil {
return nil, err
}
res = append(res, nonce)
}
return res, nil
}
// byteSliceTo66ByteSlice converts a byte slice to a 66 byte slice.
func byteSliceTo66ByteSlice(b []byte) ([musig2.PubNonceSize]byte, error) {
if len(b) != musig2.PubNonceSize {
return [musig2.PubNonceSize]byte{},
fmt.Errorf("invalid byte slice length")
}
var res [musig2.PubNonceSize]byte
copy(res[:], b)
return res, nil
}
func (m *Manager) createWithdrawalTx(ctx context.Context,
outpoints []wire.OutPoint, prevOuts map[wire.OutPoint]*wire.TxOut,
selectedWithdrawalAmount btcutil.Amount, withdrawAddr btcutil.Address,
feeRate chainfee.SatPerKWeight) (*wire.MsgTx, btcutil.Amount,
btcutil.Amount, error) {
// First Create the tx.
msgTx := wire.NewMsgTx(2)
// Add the deposit inputs to the transaction in the order the server
// signed them.
for _, outpoint := range outpoints {
msgTx.AddTxIn(&wire.TxIn{
PreviousOutPoint: outpoint,
})
}
var (
hasChange bool
dustLimit = lnwallet.DustLimitForSize(input.P2TRSize)
withdrawalAmount btcutil.Amount
changeAmount btcutil.Amount
)
// Estimate the transaction weight without change.
weight, err := withdrawalTxWeight(len(outpoints), withdrawAddr, false)
if err != nil {
return nil, 0, 0, err
}
feeWithoutChange := feeRate.FeeForWeightRoundUp(weight)
// If the user selected a fraction of the sum of the selected deposits
// to withdraw, check if a change output is needed.
totalWithdrawalAmount := withdrawalValue(prevOuts)
if selectedWithdrawalAmount > 0 {
// Estimate the transaction weight with change.
weight, err = withdrawalTxWeight(
len(outpoints), withdrawAddr, true,
)
if err != nil {
return nil, 0, 0, err
}
feeWithChange := feeRate.FeeForWeightRoundUp(weight)
// The available change that can cover fees is the total
// selected deposit amount minus the selected withdrawal amount.
change := totalWithdrawalAmount - selectedWithdrawalAmount
switch {
case change-feeWithChange >= dustLimit:
// If the change can cover the fees without turning into
// dust, add a non-dust change output.
hasChange = true
changeAmount = change - feeWithChange
withdrawalAmount = selectedWithdrawalAmount
case change-feeWithoutChange >= 0:
// If the change is dust, we give it to the miners.
hasChange = false
withdrawalAmount = selectedWithdrawalAmount
default:
// If the fees eat into our withdrawal amount, we fail
// the withdrawal.
return nil, 0, 0, fmt.Errorf("the change doesn't " +
"cover for fees. Consider lowering the fee " +
"rate or decrease the withdrawal amount")
}
} else {
// If the user wants to withdraw the full amount, we don't need
// a change output.
hasChange = false
withdrawalAmount = totalWithdrawalAmount - feeWithoutChange
}
if withdrawalAmount < dustLimit {
return nil, 0, 0, fmt.Errorf("withdrawal amount is below " +
"dust limit")
}
if changeAmount < 0 {
return nil, 0, 0, fmt.Errorf("change amount is negative")
}
// For the users convenience we check that the change amount is lower
// than each input's value. If the change amount is higher than an
// input's value, we wouldn't have to include that input into the
// transaction, saving fees.
for outpoint, txOut := range prevOuts {
if changeAmount >= btcutil.Amount(txOut.Value) {
return nil, 0, 0, fmt.Errorf("change amount %v is "+
"higher than an input value %v of input %v",
changeAmount, btcutil.Amount(txOut.Value),
outpoint)
}
}
withdrawScript, err := txscript.PayToAddrScript(withdrawAddr)
if err != nil {
return nil, 0, 0, err
}
// Create the withdrawal output.
msgTx.AddTxOut(&wire.TxOut{
Value: int64(withdrawalAmount),
PkScript: withdrawScript,
})
if hasChange {
// Send change back to the same static address.
staticAddress, err := m.cfg.AddressManager.GetStaticAddress(ctx)
if err != nil {
log.Errorf("error retrieving taproot address %v", err)
return nil, 0, 0, fmt.Errorf("withdrawal failed")
}
changeAddress, err := btcutil.NewAddressTaproot(
schnorr.SerializePubKey(staticAddress.TaprootKey),
m.cfg.ChainParams,
)
if err != nil {
return nil, 0, 0, err
}
changeScript, err := txscript.PayToAddrScript(changeAddress)
if err != nil {
return nil, 0, 0, err
}
msgTx.AddTxOut(&wire.TxOut{
Value: int64(changeAmount),
PkScript: changeScript,
})
}
return msgTx, withdrawalAmount, changeAmount, nil
}
// withdrawalFee returns the weight for the withdrawal transaction.
func withdrawalTxWeight(numInputs int, sweepAddress btcutil.Address,
hasChange bool) (lntypes.WeightUnit, error) {
var weightEstimator input.TxWeightEstimator
for i := 0; i < numInputs; i++ {
weightEstimator.AddTaprootKeySpendInput(
txscript.SigHashDefault,
)
}
// Get the weight of the sweep output.
switch sweepAddress.(type) {
case *btcutil.AddressWitnessPubKeyHash:
weightEstimator.AddP2WKHOutput()
case *btcutil.AddressTaproot:
weightEstimator.AddP2TROutput()
default:
return 0, fmt.Errorf("invalid sweep address type %T",
sweepAddress)
}
// If there's a change output add the weight of the static address.
if hasChange {
weightEstimator.AddP2TROutput()
}
return weightEstimator.Weight(), nil
}
// finalizeMusig2Transaction creates the finalized transactions for either
// the htlc or the cooperative close.
func (m *Manager) finalizeMusig2Transaction(ctx context.Context,
outpoints []wire.OutPoint, signer lndclient.SignerClient,
musig2Sessions []*input.MuSig2SessionInfo,
tx *wire.MsgTx, serverSigs [][]byte) (*wire.MsgTx, error) {
for idx := range outpoints {
haveAllSigs, finalSig, err := signer.MuSig2CombineSig(
ctx, musig2Sessions[idx].SessionID,
[][]byte{serverSigs[idx]},
)
if err != nil {
return nil, err
}
if !haveAllSigs {
return nil, fmt.Errorf("missing sigs")
}
tx.TxIn[idx].Witness = wire.TxWitness{finalSig}
}
return tx, nil
}
func toPrevoutInfo(outpoints []wire.OutPoint) []*staticaddressrpc.PrevoutInfo {
var result []*staticaddressrpc.PrevoutInfo
for _, o := range outpoints {
outP := o