77 "reflect"
88 "strings"
99
10+ "github.com/btcsuite/btcd/btcec/v2/schnorr"
1011 "github.com/btcsuite/btcd/btcec/v2/schnorr/musig2"
1112 "github.com/btcsuite/btcd/btcutil"
1213 "github.com/btcsuite/btcd/chaincfg"
@@ -75,6 +76,7 @@ type newWithdrawalRequest struct {
7576 respChan chan * newWithdrawalResponse
7677 destAddr string
7778 satPerVbyte int64
79+ amount int64
7880}
7981
8082// newWithdrawalResponse is used to return withdrawal info and error to the
@@ -156,10 +158,10 @@ func (m *Manager) Run(ctx context.Context, currentHeight uint32) error {
156158 err )
157159 }
158160
159- case request := <- m .newWithdrawalRequestChan :
161+ case req := <- m .newWithdrawalRequestChan :
160162 txHash , pkScript , err = m .WithdrawDeposits (
161- ctx , request .outpoints , request .destAddr ,
162- request .satPerVbyte ,
163+ ctx , req .outpoints , req .destAddr ,
164+ req .satPerVbyte , req . amount ,
163165 )
164166 if err != nil {
165167 log .Errorf ("Error withdrawing deposits: %v" ,
@@ -174,7 +176,7 @@ func (m *Manager) Run(ctx context.Context, currentHeight uint32) error {
174176 err : err ,
175177 }
176178 select {
177- case request .respChan <- resp :
179+ case req .respChan <- resp :
178180
179181 case <- ctx .Done ():
180182 // Notify subroutines that the main loop has
@@ -261,8 +263,8 @@ func (m *Manager) WaitInitComplete() {
261263
262264// WithdrawDeposits starts a deposits withdrawal flow.
263265func (m * Manager ) WithdrawDeposits (ctx context.Context ,
264- outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ) ( string ,
265- string , error ) {
266+ outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ,
267+ amount int64 ) ( string , string , error ) {
266268
267269 if len (outpoints ) == 0 {
268270 return "" , "" , fmt .Errorf ("no outpoints selected to " +
@@ -272,7 +274,8 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
272274 // Ensure that the deposits are in a state in which they can be
273275 // withdrawn.
274276 deposits , allActive := m .cfg .DepositManager .AllOutpointsActiveDeposits (
275- outpoints , deposit .Deposited )
277+ outpoints , deposit .Deposited ,
278+ )
276279
277280 if ! allActive {
278281 return "" , "" , ErrWithdrawingInactiveDeposits
@@ -303,7 +306,7 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
303306 }
304307
305308 finalizedTx , err := m .createFinalizedWithdrawalTx (
306- ctx , deposits , withdrawalAddress , satPerVbyte ,
309+ ctx , deposits , withdrawalAddress , satPerVbyte , amount ,
307310 )
308311 if err != nil {
309312 return "" , "" , err
@@ -355,7 +358,8 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
355358
356359func (m * Manager ) createFinalizedWithdrawalTx (ctx context.Context ,
357360 deposits []* deposit.Deposit , withdrawalAddress btcutil.Address ,
358- satPerVbyte int64 ) (* wire.MsgTx , error ) {
361+ satPerVbyte int64 , selectedWithdrawalAmount int64 ) (* wire.MsgTx ,
362+ error ) {
359363
360364 // Create a musig2 session for each deposit.
361365 withdrawalSessions , clientNonces , err := m .createMusig2Sessions (
@@ -380,54 +384,55 @@ func (m *Manager) createFinalizedWithdrawalTx(ctx context.Context,
380384 ).FeePerKWeight ()
381385 }
382386
383- // We'll now check the selected fee rate leaves a withdrawal output that
384- // is above the dust limit. If not we cancel the withdrawal instead of
385- // requesting a signature from the server.
386- addressParams , err := m .cfg .AddressManager .GetStaticAddressParameters (
387+ params , err := m .cfg .AddressManager .GetStaticAddressParameters (
387388 ctx ,
388389 )
389390 if err != nil {
390391 return nil , fmt .Errorf ("couldn't get confirmation height for " +
391392 "deposit, %w" , err )
392393 }
393394
394- // Calculate the fee value in satoshis.
395- outpoints := toOutpoints (deposits )
396- weight , err := withdrawalFee (len (outpoints ), withdrawalAddress )
395+ // Send change back to the static address.
396+ staticAddress , err := m .cfg .AddressManager .GetStaticAddress (ctx )
397397 if err != nil {
398- return nil , err
398+ log .Warnf ("error retrieving taproot address %w" , err )
399+
400+ return nil , fmt .Errorf ("withdrawal failed" )
399401 }
400- feeValue := withdrawalSweepFeeRate .FeeForWeight (weight )
401402
402- var (
403- prevOuts = m .toPrevOuts (deposits , addressParams .PkScript )
404- totalValue = withdrawalValue (prevOuts )
405- outputValue = int64 (totalValue ) - int64 (feeValue )
406- // P2TRSize calculates a dust limit based on a 40 byte maximum
407- // size witness output.
408- dustLimit = lnwallet .DustLimitForSize (input .P2TRSize )
403+ changeAddress , err := btcutil .NewAddressTaproot (
404+ schnorr .SerializePubKey (staticAddress .TaprootKey ),
405+ m .cfg .ChainParams ,
409406 )
410-
411- if outputValue < int64 (dustLimit ) {
412- return nil , fmt .Errorf ("withdrawal output value %d sats " +
413- "below dust limit %d sats" , outputValue , dustLimit )
407+ if err != nil {
408+ return nil , err
414409 }
415410
416- resp , err := m .cfg .StaticAddressServerClient .ServerWithdrawDeposits (
417- ctx , & staticaddressrpc.ServerWithdrawRequest {
418- Outpoints : toPrevoutInfo (outpoints ),
419- ClientNonces : clientNonces ,
420- ClientSweepAddr : withdrawalAddress .String (),
421- TxFeeRate : uint64 (withdrawalSweepFeeRate ),
422- },
411+ outpoints := toOutpoints (deposits )
412+ prevOuts := m .toPrevOuts (deposits , params .PkScript )
413+ totalValue := withdrawalValue (prevOuts )
414+ withdrawalTx , withdrawAmount , changeAmount , err := m .createWithdrawalTx (
415+ outpoints , totalValue , btcutil .Amount (selectedWithdrawalAmount ),
416+ withdrawalAddress , changeAddress , withdrawalSweepFeeRate ,
423417 )
424418 if err != nil {
425419 return nil , err
426420 }
427421
428- withdrawalOutputValue := int64 (totalValue - feeValue )
429- withdrawalTx , err := m .createWithdrawalTx (
430- outpoints , withdrawalOutputValue , withdrawalAddress ,
422+ // Request the server to sign the withdrawal transaction.
423+ //
424+ // The withdrawal and change amount are sent to the server with the
425+ // expectation that the server just signs the transaction, without
426+ // performing fee calculations and dust considerations. The client is
427+ // responsible for that.
428+ resp , err := m .cfg .StaticAddressServerClient .ServerWithdrawDeposits (
429+ ctx , & staticaddressrpc.ServerWithdrawRequest {
430+ Outpoints : toPrevoutInfo (outpoints ),
431+ ClientNonces : clientNonces ,
432+ ClientWithdrawalAddr : withdrawalAddress .String (),
433+ WithdrawAmount : int64 (withdrawAmount ),
434+ ChangeAmount : int64 (changeAmount ),
435+ },
431436 )
432437 if err != nil {
433438 return nil , err
@@ -635,8 +640,10 @@ func byteSliceTo66ByteSlice(b []byte) ([musig2.PubNonceSize]byte, error) {
635640}
636641
637642func (m * Manager ) createWithdrawalTx (outpoints []wire.OutPoint ,
638- withdrawlOutputValue int64 , clientSweepAddress btcutil.Address ) (
639- * wire.MsgTx , error ) {
643+ totalWithdrawalAmount btcutil.Amount ,
644+ selectedWithdrawalAmount btcutil.Amount , withdrawAddr btcutil.Address ,
645+ changeAddress * btcutil.AddressTaproot , feeRate chainfee.SatPerKWeight ) (
646+ * wire.MsgTx , btcutil.Amount , btcutil.Amount , error ) {
640647
641648 // First Create the tx.
642649 msgTx := wire .NewMsgTx (2 )
@@ -649,25 +656,101 @@ func (m *Manager) createWithdrawalTx(outpoints []wire.OutPoint,
649656 })
650657 }
651658
652- pkscript , err := txscript .PayToAddrScript (clientSweepAddress )
659+ var (
660+ hasChange bool
661+ dustLimit = lnwallet .DustLimitForSize (input .P2TRSize )
662+ withdrawalAmount btcutil.Amount
663+ changeAmount btcutil.Amount
664+ )
665+
666+ // Estimate the transaction weight without change.
667+ weight , err := withdrawalTxWeight (len (outpoints ), withdrawAddr , false )
653668 if err != nil {
654- return nil , err
669+ return nil , 0 , 0 , err
655670 }
671+ feeWithoutChange := feeRate .FeeForWeight (weight )
656672
657- // Create the sweep output
658- sweepOutput := & wire.TxOut {
659- Value : withdrawlOutputValue ,
660- PkScript : pkscript ,
673+ // If the user selected a fraction of the sum of the selected deposits
674+ // to withdraw, check if a change output is needed.
675+ if selectedWithdrawalAmount > 0 {
676+ // Estimate the transaction weight with change.
677+ weight , err = withdrawalTxWeight (
678+ len (outpoints ), withdrawAddr , true ,
679+ )
680+ if err != nil {
681+ return nil , 0 , 0 , err
682+ }
683+ feeWithChange := feeRate .FeeForWeight (weight )
684+
685+ // The available change that can cover fees is the total
686+ // selected deposit amount minus the selected withdrawal amount.
687+ change := totalWithdrawalAmount - selectedWithdrawalAmount
688+
689+ switch {
690+ case change - feeWithChange >= dustLimit :
691+ // If the change can cover the fees without turning into
692+ // dust, add a non-dust change output.
693+ hasChange = true
694+ changeAmount = change - feeWithChange
695+ withdrawalAmount = selectedWithdrawalAmount
696+
697+ case change - feeWithChange >= 0 :
698+ // If the change is dust, we give it to the miners.
699+ hasChange = false
700+ withdrawalAmount = selectedWithdrawalAmount
701+
702+ default :
703+ // If the fees eat into our withdrawal amount, we fail
704+ // the withdrawal.
705+ return nil , 0 , 0 , fmt .Errorf ("the change doesn't " +
706+ "cover for fees. Consider lowering the fee " +
707+ "rate or increase the withdrawal amount" )
708+ }
709+ } else {
710+ // If the user wants to withdraw the full amount, we don't need
711+ // a change output.
712+ hasChange = false
713+ withdrawalAmount = totalWithdrawalAmount - feeWithoutChange
661714 }
662715
663- msgTx .AddTxOut (sweepOutput )
716+ if withdrawalAmount < dustLimit {
717+ return nil , 0 , 0 , fmt .Errorf ("withdrawal amount is below " +
718+ "dust limit" )
719+ }
720+
721+ if changeAmount < 0 {
722+ return nil , 0 , 0 , fmt .Errorf ("change amount is negative" )
723+ }
724+
725+ withdrawScript , err := txscript .PayToAddrScript (withdrawAddr )
726+ if err != nil {
727+ return nil , 0 , 0 , err
728+ }
664729
665- return msgTx , nil
730+ // Create the withdrawal output.
731+ msgTx .AddTxOut (& wire.TxOut {
732+ Value : int64 (withdrawalAmount ),
733+ PkScript : withdrawScript ,
734+ })
735+
736+ if hasChange {
737+ changeScript , err := txscript .PayToAddrScript (changeAddress )
738+ if err != nil {
739+ return nil , 0 , 0 , err
740+ }
741+
742+ msgTx .AddTxOut (& wire.TxOut {
743+ Value : int64 (changeAmount ),
744+ PkScript : changeScript ,
745+ })
746+ }
747+
748+ return msgTx , withdrawalAmount , changeAmount , nil
666749}
667750
668751// withdrawalFee returns the weight for the withdrawal transaction.
669- func withdrawalFee (numInputs int ,
670- sweepAddress btcutil. Address ) (lntypes.WeightUnit , error ) {
752+ func withdrawalTxWeight (numInputs int , sweepAddress btcutil. Address ,
753+ hasChange bool ) (lntypes.WeightUnit , error ) {
671754
672755 var weightEstimator input.TxWeightEstimator
673756 for i := 0 ; i < numInputs ; i ++ {
@@ -689,6 +772,11 @@ func withdrawalFee(numInputs int,
689772 sweepAddress )
690773 }
691774
775+ // If there's a change output add the weight of the static address.
776+ if hasChange {
777+ weightEstimator .AddP2TROutput ()
778+ }
779+
692780 return weightEstimator .Weight (), nil
693781}
694782
@@ -827,13 +915,14 @@ func (m *Manager) republishWithdrawals(ctx context.Context) error {
827915// DeliverWithdrawalRequest forwards a withdrawal request to the manager main
828916// loop.
829917func (m * Manager ) DeliverWithdrawalRequest (ctx context.Context ,
830- outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ) ( string ,
831- string , error ) {
918+ outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ,
919+ amount int64 ) ( string , string , error ) {
832920
833921 request := newWithdrawalRequest {
834922 outpoints : outpoints ,
835923 destAddr : destAddr ,
836924 satPerVbyte : satPerVbyte ,
925+ amount : amount ,
837926 respChan : make (chan * newWithdrawalResponse ),
838927 }
839928
0 commit comments