1
1
package loopin
2
2
3
3
import (
4
+ "bytes"
4
5
"context"
5
6
"errors"
6
7
"fmt"
@@ -93,6 +94,8 @@ type StaticAddressLoopIn struct {
93
94
// swap.
94
95
DepositOutpoints []string
95
96
97
+ SelectedAmount btcutil.Amount
98
+
96
99
// state is the current state of the swap.
97
100
state fsm.StateType
98
101
@@ -287,10 +290,20 @@ func (l *StaticAddressLoopIn) createHtlcTx(chainParams *chaincfg.Params,
287
290
weight := l .htlcWeight ()
288
291
fee := feeRate .FeeForWeight (weight )
289
292
290
- // Check if the server breaches our fee limits.
291
- amt := float64 (l .TotalDepositAmount ())
292
- feeLimit := btcutil .Amount (amt * maxFeePercentage )
293
+ // Determine the swap amount. If the user selected a specific amount, we
294
+ // use that and use the difference to the total deposit amount as the
295
+ // change.
296
+ var (
297
+ swapAmt = float64 (l .TotalDepositAmount ())
298
+ changeAmount btcutil.Amount
299
+ )
300
+ if l .SelectedAmount > 0 {
301
+ swapAmt = float64 (l .SelectedAmount )
302
+ changeAmount = l .TotalDepositAmount () - l .SelectedAmount
303
+ }
293
304
305
+ // Check if the server breaches our fee limits.
306
+ feeLimit := btcutil .Amount (swapAmt * maxFeePercentage )
294
307
if fee > feeLimit {
295
308
return nil , fmt .Errorf ("htlc tx fee %v exceeds max fee %v" ,
296
309
fee , feeLimit )
@@ -314,6 +327,14 @@ func (l *StaticAddressLoopIn) createHtlcTx(chainParams *chaincfg.Params,
314
327
315
328
msgTx .AddTxOut (sweepOutput )
316
329
330
+ // We expect change to be sent back to our static address output script.
331
+ if changeAmount > 0 {
332
+ msgTx .AddTxOut (& wire.TxOut {
333
+ Value : int64 (changeAmount ),
334
+ PkScript : l .AddressParams .PkScript ,
335
+ })
336
+ }
337
+
317
338
return msgTx , nil
318
339
}
319
340
@@ -373,11 +394,24 @@ func (l *StaticAddressLoopIn) createHtlcSweepTx(ctx context.Context,
373
394
return nil , err
374
395
}
375
396
397
+ // Check if the htlc tx has a change output. If so we need to select the
398
+ // non-change output index to construct the sweep with.
399
+ htlcInputIndex := uint32 (0 )
400
+ if len (htlcTx .TxOut ) == 2 {
401
+ // If the first htlc tx output matches our static address
402
+ // script we need to select the second output to sweep from.
403
+ if bytes .Equal (
404
+ htlcTx .TxOut [0 ].PkScript , l .AddressParams .PkScript ,
405
+ ) {
406
+ htlcInputIndex = 1
407
+ }
408
+ }
409
+
376
410
// Add the htlc input.
377
411
sweepTx .AddTxIn (& wire.TxIn {
378
412
PreviousOutPoint : wire.OutPoint {
379
413
Hash : htlcTx .TxHash (),
380
- Index : 0 ,
414
+ Index : htlcInputIndex ,
381
415
},
382
416
SignatureScript : htlc .SigScript ,
383
417
Sequence : htlc .SuccessSequence (),
0 commit comments