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
@@ -259,10 +261,11 @@ func (m *Manager) WaitInitComplete() {
259261 <- m .initChan
260262}
261263
262- // WithdrawDeposits starts a deposits withdrawal flow.
264+ // WithdrawDeposits starts a deposits withdrawal flow. If the amount is set to 0
265+ // the full amount of the selected deposits will be withdrawn.
263266func (m * Manager ) WithdrawDeposits (ctx context.Context ,
264- outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ) ( string ,
265- string , error ) {
267+ outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ,
268+ amount int64 ) ( string , string , error ) {
266269
267270 if len (outpoints ) == 0 {
268271 return "" , "" , fmt .Errorf ("no outpoints selected to " +
@@ -272,7 +275,8 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
272275 // Ensure that the deposits are in a state in which they can be
273276 // withdrawn.
274277 deposits , allActive := m .cfg .DepositManager .AllOutpointsActiveDeposits (
275- outpoints , deposit .Deposited )
278+ outpoints , deposit .Deposited ,
279+ )
276280
277281 if ! allActive {
278282 return "" , "" , ErrWithdrawingInactiveDeposits
@@ -303,7 +307,7 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
303307 }
304308
305309 finalizedTx , err := m .createFinalizedWithdrawalTx (
306- ctx , deposits , withdrawalAddress , satPerVbyte ,
310+ ctx , deposits , withdrawalAddress , satPerVbyte , amount ,
307311 )
308312 if err != nil {
309313 return "" , "" , err
@@ -355,7 +359,8 @@ func (m *Manager) WithdrawDeposits(ctx context.Context,
355359
356360func (m * Manager ) createFinalizedWithdrawalTx (ctx context.Context ,
357361 deposits []* deposit.Deposit , withdrawalAddress btcutil.Address ,
358- satPerVbyte int64 ) (* wire.MsgTx , error ) {
362+ satPerVbyte int64 , selectedWithdrawalAmount int64 ) (* wire.MsgTx ,
363+ error ) {
359364
360365 // Create a musig2 session for each deposit.
361366 withdrawalSessions , clientNonces , err := m .createMusig2Sessions (
@@ -380,54 +385,53 @@ func (m *Manager) createFinalizedWithdrawalTx(ctx context.Context,
380385 ).FeePerKWeight ()
381386 }
382387
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- ctx ,
388- )
388+ params , err := m .cfg .AddressManager .GetStaticAddressParameters (ctx )
389389 if err != nil {
390390 return nil , fmt .Errorf ("couldn't get confirmation height for " +
391391 "deposit, %w" , err )
392392 }
393393
394- // Calculate the fee value in satoshis.
395- outpoints := toOutpoints (deposits )
396- weight , err := withdrawalFee (len (outpoints ), withdrawalAddress )
394+ // Send change back to the same static address.
395+ staticAddress , err := m .cfg .AddressManager .GetStaticAddress (ctx )
397396 if err != nil {
398- return nil , err
397+ log .Warnf ("error retrieving taproot address %w" , err )
398+
399+ return nil , fmt .Errorf ("withdrawal failed" )
399400 }
400- feeValue := withdrawalSweepFeeRate .FeeForWeight (weight )
401401
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 )
402+ changeAddress , err := btcutil .NewAddressTaproot (
403+ schnorr .SerializePubKey (staticAddress .TaprootKey ),
404+ m .cfg .ChainParams ,
409405 )
410-
411- if outputValue < int64 (dustLimit ) {
412- return nil , fmt .Errorf ("withdrawal output value %d sats " +
413- "below dust limit %d sats" , outputValue , dustLimit )
406+ if err != nil {
407+ return nil , err
414408 }
415409
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- },
410+ outpoints := toOutpoints (deposits )
411+ prevOuts := m .toPrevOuts (deposits , params .PkScript )
412+ totalValue := withdrawalValue (prevOuts )
413+ withdrawalTx , withdrawAmount , changeAmount , err := m .createWithdrawalTx (
414+ outpoints , totalValue , btcutil .Amount (selectedWithdrawalAmount ),
415+ withdrawalAddress , changeAddress , withdrawalSweepFeeRate ,
423416 )
424417 if err != nil {
425418 return nil , err
426419 }
427420
428- withdrawalOutputValue := int64 (totalValue - feeValue )
429- withdrawalTx , err := m .createWithdrawalTx (
430- outpoints , withdrawalOutputValue , withdrawalAddress ,
421+ // Request the server to sign the withdrawal transaction.
422+ //
423+ // The withdrawal and change amount are sent to the server with the
424+ // expectation that the server just signs the transaction, without
425+ // performing fee calculations and dust considerations. The client is
426+ // responsible for that.
427+ resp , err := m .cfg .StaticAddressServerClient .ServerWithdrawDeposits (
428+ ctx , & staticaddressrpc.ServerWithdrawRequest {
429+ Outpoints : toPrevoutInfo (outpoints ),
430+ ClientNonces : clientNonces ,
431+ ClientWithdrawalAddr : withdrawalAddress .String (),
432+ WithdrawAmount : int64 (withdrawAmount ),
433+ ChangeAmount : int64 (changeAmount ),
434+ },
431435 )
432436 if err != nil {
433437 return nil , err
@@ -635,8 +639,10 @@ func byteSliceTo66ByteSlice(b []byte) ([musig2.PubNonceSize]byte, error) {
635639}
636640
637641func (m * Manager ) createWithdrawalTx (outpoints []wire.OutPoint ,
638- withdrawlOutputValue int64 , clientSweepAddress btcutil.Address ) (
639- * wire.MsgTx , error ) {
642+ totalWithdrawalAmount btcutil.Amount ,
643+ selectedWithdrawalAmount btcutil.Amount , withdrawAddr btcutil.Address ,
644+ changeAddress * btcutil.AddressTaproot , feeRate chainfee.SatPerKWeight ) (
645+ * wire.MsgTx , btcutil.Amount , btcutil.Amount , error ) {
640646
641647 // First Create the tx.
642648 msgTx := wire .NewMsgTx (2 )
@@ -649,25 +655,101 @@ func (m *Manager) createWithdrawalTx(outpoints []wire.OutPoint,
649655 })
650656 }
651657
652- pkscript , err := txscript .PayToAddrScript (clientSweepAddress )
658+ var (
659+ hasChange bool
660+ dustLimit = lnwallet .DustLimitForSize (input .P2TRSize )
661+ withdrawalAmount btcutil.Amount
662+ changeAmount btcutil.Amount
663+ )
664+
665+ // Estimate the transaction weight without change.
666+ weight , err := withdrawalTxWeight (len (outpoints ), withdrawAddr , false )
653667 if err != nil {
654- return nil , err
668+ return nil , 0 , 0 , err
669+ }
670+ feeWithoutChange := feeRate .FeeForWeight (weight )
671+
672+ // If the user selected a fraction of the sum of the selected deposits
673+ // to withdraw, check if a change output is needed.
674+ if selectedWithdrawalAmount > 0 {
675+ // Estimate the transaction weight with change.
676+ weight , err = withdrawalTxWeight (
677+ len (outpoints ), withdrawAddr , true ,
678+ )
679+ if err != nil {
680+ return nil , 0 , 0 , err
681+ }
682+ feeWithChange := feeRate .FeeForWeight (weight )
683+
684+ // The available change that can cover fees is the total
685+ // selected deposit amount minus the selected withdrawal amount.
686+ change := totalWithdrawalAmount - selectedWithdrawalAmount
687+
688+ switch {
689+ case change - feeWithChange >= dustLimit :
690+ // If the change can cover the fees without turning into
691+ // dust, add a non-dust change output.
692+ hasChange = true
693+ changeAmount = change - feeWithChange
694+ withdrawalAmount = selectedWithdrawalAmount
695+
696+ case change - feeWithoutChange >= 0 :
697+ // If the change is dust, we give it to the miners.
698+ hasChange = false
699+ withdrawalAmount = selectedWithdrawalAmount
700+
701+ default :
702+ // If the fees eat into our withdrawal amount, we fail
703+ // the withdrawal.
704+ return nil , 0 , 0 , fmt .Errorf ("the change doesn't " +
705+ "cover for fees. Consider lowering the fee " +
706+ "rate or decrease the withdrawal amount" )
707+ }
708+ } else {
709+ // If the user wants to withdraw the full amount, we don't need
710+ // a change output.
711+ hasChange = false
712+ withdrawalAmount = totalWithdrawalAmount - feeWithoutChange
713+ }
714+
715+ if withdrawalAmount < dustLimit {
716+ return nil , 0 , 0 , fmt .Errorf ("withdrawal amount is below " +
717+ "dust limit" )
718+ }
719+
720+ if changeAmount < 0 {
721+ return nil , 0 , 0 , fmt .Errorf ("change amount is negative" )
655722 }
656723
657- // Create the sweep output
658- sweepOutput := & wire.TxOut {
659- Value : withdrawlOutputValue ,
660- PkScript : pkscript ,
724+ withdrawScript , err := txscript .PayToAddrScript (withdrawAddr )
725+ if err != nil {
726+ return nil , 0 , 0 , err
661727 }
662728
663- msgTx .AddTxOut (sweepOutput )
729+ // Create the withdrawal output.
730+ msgTx .AddTxOut (& wire.TxOut {
731+ Value : int64 (withdrawalAmount ),
732+ PkScript : withdrawScript ,
733+ })
734+
735+ if hasChange {
736+ changeScript , err := txscript .PayToAddrScript (changeAddress )
737+ if err != nil {
738+ return nil , 0 , 0 , err
739+ }
664740
665- return msgTx , nil
741+ msgTx .AddTxOut (& wire.TxOut {
742+ Value : int64 (changeAmount ),
743+ PkScript : changeScript ,
744+ })
745+ }
746+
747+ return msgTx , withdrawalAmount , changeAmount , nil
666748}
667749
668750// withdrawalFee returns the weight for the withdrawal transaction.
669- func withdrawalFee (numInputs int ,
670- sweepAddress btcutil. Address ) (lntypes.WeightUnit , error ) {
751+ func withdrawalTxWeight (numInputs int , sweepAddress btcutil. Address ,
752+ hasChange bool ) (lntypes.WeightUnit , error ) {
671753
672754 var weightEstimator input.TxWeightEstimator
673755 for i := 0 ; i < numInputs ; i ++ {
@@ -689,6 +771,11 @@ func withdrawalFee(numInputs int,
689771 sweepAddress )
690772 }
691773
774+ // If there's a change output add the weight of the static address.
775+ if hasChange {
776+ weightEstimator .AddP2TROutput ()
777+ }
778+
692779 return weightEstimator .Weight (), nil
693780}
694781
@@ -827,13 +914,14 @@ func (m *Manager) republishWithdrawals(ctx context.Context) error {
827914// DeliverWithdrawalRequest forwards a withdrawal request to the manager main
828915// loop.
829916func (m * Manager ) DeliverWithdrawalRequest (ctx context.Context ,
830- outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ) ( string ,
831- string , error ) {
917+ outpoints []wire.OutPoint , destAddr string , satPerVbyte int64 ,
918+ amount int64 ) ( string , string , error ) {
832919
833920 request := newWithdrawalRequest {
834921 outpoints : outpoints ,
835922 destAddr : destAddr ,
836923 satPerVbyte : satPerVbyte ,
924+ amount : amount ,
837925 respChan : make (chan * newWithdrawalResponse ),
838926 }
839927
0 commit comments