-
Notifications
You must be signed in to change notification settings - Fork 456
Expand file tree
/
Copy pathfunding.rs
More file actions
2478 lines (2221 loc) · 91.2 KB
/
funding.rs
File metadata and controls
2478 lines (2221 loc) · 91.2 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
// This file is Copyright its original authors, visible in version control
// history.
//
// This file is licensed under the Apache License, Version 2.0 <LICENSE-APACHE
// or http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your option.
// You may not use this file except in accordance with one or both of these
// licenses.
//! Types pertaining to funding channels.
use bitcoin::hashes::Hash;
use bitcoin::secp256k1::PublicKey;
use bitcoin::{Amount, FeeRate, OutPoint, ScriptBuf, SignedAmount, TxOut, WScriptHash, Weight};
use crate::ln::chan_utils::{
make_funding_redeemscript, BASE_INPUT_WEIGHT, EMPTY_SCRIPT_SIG_WEIGHT,
FUNDING_TRANSACTION_WITNESS_WEIGHT,
};
use crate::ln::interactivetxs::{get_output_weight, TX_COMMON_FIELDS_WEIGHT};
use crate::ln::msgs;
use crate::ln::types::ChannelId;
use crate::ln::LN_MAX_MSG_LEN;
use crate::prelude::*;
use crate::util::async_poll::MaybeSend;
use crate::util::wallet_utils::{
CoinSelection, CoinSelectionSource, CoinSelectionSourceSync, Input,
};
/// Error returned when the acceptor's contribution cannot accommodate the initiator's proposed
/// feerate.
///
/// When building a [`FundingContribution`], fees are estimated at `min_feerate` assuming initiator
/// responsibility. If the counterparty also initiates a splice and wins the tie-break, they become
/// the initiator and choose the feerate. The fee is then re-estimated at the counterparty's
/// feerate for only our contributed inputs and outputs. When this re-estimation fails, the
/// contribution is dropped and the counterparty's splice proceeds without it.
///
/// See [`ChannelManager::splice_channel`] for further details.
///
/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
#[derive(Debug)]
pub(super) enum FeeRateAdjustmentError {
/// The counterparty's proposed feerate is below `min_feerate`, which was used as the feerate
/// during coin selection. We'll retry via RBF at our preferred feerate.
FeeRateTooLow { target_feerate: FeeRate, min_feerate: FeeRate },
/// The counterparty's proposed feerate is above `max_feerate` and the re-estimated fee for
/// our contributed inputs and outputs exceeds the original fee estimate (computed at
/// `min_feerate` assuming initiator responsibility). If the re-estimated fee were within the
/// original estimate, a feerate above `max_feerate` would be tolerable since the acceptor
/// doesn't pay for common fields or the shared input/output.
FeeRateTooHigh {
target_feerate: FeeRate,
max_feerate: FeeRate,
target_fee: Amount,
original_fee: Amount,
},
/// Arithmetic overflow when computing the fee buffer.
FeeBufferOverflow,
/// The re-estimated fee exceeds the available fee buffer regardless of `max_feerate`. The fee
/// buffer is the maximum fee that can be accommodated:
/// - **splice-in**: the selected inputs' value minus the contributed amount
/// - **splice-out**: the channel balance minus the withdrawal outputs
FeeBufferInsufficient { source: &'static str, available: Amount, required: Amount },
}
impl core::fmt::Display for FeeRateAdjustmentError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FeeRateAdjustmentError::FeeRateTooLow { target_feerate, min_feerate } => {
write!(
f,
"Target feerate {} is below our minimum {}; \
proceeding without contribution, will RBF later",
target_feerate, min_feerate,
)
},
FeeRateAdjustmentError::FeeRateTooHigh {
target_feerate,
max_feerate,
target_fee,
original_fee,
} => {
write!(
f,
"Target feerate {} exceeds our maximum {} and target fee {} exceeds original fee estimate {}",
target_feerate, max_feerate, target_fee, original_fee,
)
},
FeeRateAdjustmentError::FeeBufferOverflow => {
write!(
f,
"Arithmetic overflow when computing available fee buffer; \
proceeding without contribution",
)
},
FeeRateAdjustmentError::FeeBufferInsufficient { source, available, required } => {
write!(
f,
"Fee buffer {} ({}) is insufficient for required fee {}; \
proceeding without contribution",
available, source, required,
)
},
}
}
}
/// Error returned when building a [`FundingContribution`] from a [`FundingTemplate`].
#[derive(Debug)]
pub enum FundingContributionError {
/// The feerate exceeds the maximum allowed feerate.
FeeRateExceedsMaximum {
/// The requested feerate.
feerate: FeeRate,
/// The maximum allowed feerate.
max_feerate: FeeRate,
},
/// The feerate is below the minimum RBF feerate.
///
/// Note: [`FundingTemplate::min_rbf_feerate`] may be derived from an in-progress
/// negotiation that later aborts, leaving a stale (higher than necessary) minimum. If
/// this error occurs after receiving [`Event::SpliceFailed`], call
/// [`ChannelManager::splice_channel`] again to get a fresh template.
///
/// [`Event::SpliceFailed`]: crate::events::Event::SpliceFailed
/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
FeeRateBelowRbfMinimum {
/// The requested feerate.
feerate: FeeRate,
/// The minimum RBF feerate.
min_rbf_feerate: FeeRate,
},
/// The splice value is invalid (zero, empty outputs, or exceeds the maximum money supply).
InvalidSpliceValue,
/// Coin selection failed to find suitable inputs.
CoinSelectionFailed,
/// This is not an RBF scenario (no minimum RBF feerate available).
NotRbfScenario,
}
impl core::fmt::Display for FundingContributionError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
FundingContributionError::FeeRateExceedsMaximum { feerate, max_feerate } => {
write!(f, "Feerate {} exceeds maximum {}", feerate, max_feerate)
},
FundingContributionError::FeeRateBelowRbfMinimum { feerate, min_rbf_feerate } => {
write!(f, "Feerate {} is below minimum RBF feerate {}", feerate, min_rbf_feerate)
},
FundingContributionError::InvalidSpliceValue => {
write!(f, "Invalid splice value (zero, empty, or exceeds limit)")
},
FundingContributionError::CoinSelectionFailed => {
write!(f, "Coin selection failed to find suitable inputs")
},
FundingContributionError::NotRbfScenario => {
write!(f, "Not an RBF scenario (no minimum RBF feerate)")
},
}
}
}
/// The user's prior contribution from a previous splice negotiation on this channel.
///
/// When a pending splice exists with negotiated candidates, the prior contribution is
/// available for reuse (e.g., to bump the feerate via RBF). Contains the raw contribution and
/// the holder's balance for deferred feerate adjustment in [`FundingTemplate::rbf_sync`] or
/// [`FundingTemplate::rbf`].
///
/// Use [`FundingTemplate::prior_contribution`] to inspect the prior contribution before
/// deciding whether to call [`FundingTemplate::rbf_sync`] or one of the splice methods
/// with different parameters.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(super) struct PriorContribution {
contribution: FundingContribution,
/// The holder's balance, used for feerate adjustment. `None` when the balance computation
/// fails, in which case adjustment is skipped and coin selection is re-run.
///
/// This value is captured at [`ChannelManager::splice_channel`] time and may become stale
/// if balances change before the contribution is used. Staleness is acceptable here because
/// this is only used as an optimization to determine if the prior contribution can be
/// reused with adjusted fees — the contribution is re-validated at
/// [`ChannelManager::funding_contributed`] time and again at quiescence time against the
/// current balances.
///
/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
/// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed
holder_balance: Option<Amount>,
}
impl PriorContribution {
pub(super) fn new(contribution: FundingContribution, holder_balance: Option<Amount>) -> Self {
Self { contribution, holder_balance }
}
}
/// A template for contributing to a channel's splice funding transaction.
///
/// This is returned from [`ChannelManager::splice_channel`] when a channel is ready to be
/// spliced. A [`FundingContribution`] must be obtained from it and passed to
/// [`ChannelManager::funding_contributed`] in order to resume the splicing process.
///
/// # Building a Contribution
///
/// For a fresh splice (no pending splice to replace), build a new contribution using one of
/// the splice methods:
/// - [`FundingTemplate::splice_in_sync`] to add funds to the channel
/// - [`FundingTemplate::splice_out_sync`] to remove funds from the channel
/// - [`FundingTemplate::splice_in_and_out_sync`] to do both
///
/// These perform coin selection and require `min_feerate` and `max_feerate` parameters.
///
/// # Replace By Fee (RBF)
///
/// When a pending splice exists that hasn't been locked yet, use [`FundingTemplate::rbf_sync`]
/// (or [`FundingTemplate::rbf`] for async) to build an RBF contribution. This handles the
/// prior contribution logic internally — reusing an adjusted prior when possible, re-running
/// coin selection when needed, or creating a fee-bump-only contribution.
///
/// Check [`FundingTemplate::min_rbf_feerate`] for the minimum feerate required (the greater of
/// the previous feerate + 25 sat/kwu and the spec's 25/24 rule). Use
/// [`FundingTemplate::prior_contribution`] to inspect the prior
/// contribution's parameters (e.g., [`FundingContribution::value_added`],
/// [`FundingContribution::outputs`]) before deciding whether to reuse it via the RBF methods
/// or build a fresh contribution with different parameters using the splice methods above.
///
/// [`ChannelManager::splice_channel`]: crate::ln::channelmanager::ChannelManager::splice_channel
/// [`ChannelManager::funding_contributed`]: crate::ln::channelmanager::ChannelManager::funding_contributed
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FundingTemplate {
/// The shared input, which, if present indicates the funding template is for a splice funding
/// transaction.
shared_input: Option<Input>,
/// The minimum RBF feerate (the greater of previous feerate + 25 sat/kwu and the spec's
/// 25/24 rule), if this template is for an RBF attempt. `None` for fresh splices with no
/// pending splice candidates.
min_rbf_feerate: Option<FeeRate>,
/// The user's prior contribution from a previous splice negotiation, if available.
prior_contribution: Option<PriorContribution>,
}
impl FundingTemplate {
/// Constructs a [`FundingTemplate`] for a splice using the provided shared input.
pub(super) fn new(
shared_input: Option<Input>, min_rbf_feerate: Option<FeeRate>,
prior_contribution: Option<PriorContribution>,
) -> Self {
Self { shared_input, min_rbf_feerate, prior_contribution }
}
/// Returns the minimum RBF feerate, if this template is for an RBF attempt.
///
/// When set, the `min_feerate` passed to the splice methods (e.g.,
/// [`FundingTemplate::splice_in_sync`]) must be at least this value.
pub fn min_rbf_feerate(&self) -> Option<FeeRate> {
self.min_rbf_feerate
}
/// Returns a reference to the prior contribution from a previous splice negotiation, if
/// available.
///
/// Use this to inspect the prior contribution's parameters (e.g.,
/// [`FundingContribution::value_added`], [`FundingContribution::outputs`]) before deciding
/// whether to reuse it via [`FundingTemplate::rbf_sync`] or build a fresh contribution
/// with different parameters using the splice methods.
///
/// Note: the returned contribution may reflect a different feerate than originally provided,
/// as it may have been adjusted for RBF or for the counterparty's feerate when acting as
/// the acceptor. This can change other parameters too (e.g.,
/// [`FundingContribution::value_added`] may be higher if the change output was removed to
/// cover a higher fee).
pub fn prior_contribution(&self) -> Option<&FundingContribution> {
self.prior_contribution.as_ref().map(|p| &p.contribution)
}
}
macro_rules! build_funding_contribution {
($value_added:expr, $outputs:expr, $shared_input:expr, $min_rbf_feerate:expr, $feerate:expr, $max_feerate:expr, $force_coin_selection:expr, $wallet:ident, $($await:tt)*) => {{
let value_added: Amount = $value_added;
let outputs: Vec<TxOut> = $outputs;
let shared_input: Option<Input> = $shared_input;
let min_rbf_feerate: Option<FeeRate> = $min_rbf_feerate;
let feerate: FeeRate = $feerate;
let max_feerate: FeeRate = $max_feerate;
let force_coin_selection: bool = $force_coin_selection;
if feerate > max_feerate {
return Err(FundingContributionError::FeeRateExceedsMaximum { feerate, max_feerate });
}
if let Some(min_rbf_feerate) = min_rbf_feerate {
if feerate < min_rbf_feerate {
return Err(FundingContributionError::FeeRateBelowRbfMinimum { feerate, min_rbf_feerate });
}
}
// Validate user-provided amounts are within MAX_MONEY before coin selection to
// ensure FundingContribution::net_value() arithmetic cannot overflow. With all
// amounts bounded by MAX_MONEY (~2.1e15 sat), the worst-case net_value()
// computation is -2 * MAX_MONEY (~-4.2e15), well within i64::MIN (~-9.2e18).
if value_added > Amount::MAX_MONEY {
return Err(FundingContributionError::InvalidSpliceValue);
}
let mut value_removed = Amount::ZERO;
for txout in outputs.iter() {
value_removed = match value_removed.checked_add(txout.value) {
Some(sum) if sum <= Amount::MAX_MONEY => sum,
_ => return Err(FundingContributionError::InvalidSpliceValue),
};
}
let is_splice = shared_input.is_some();
let coin_selection = if value_added == Amount::ZERO && !force_coin_selection {
CoinSelection { confirmed_utxos: vec![], change_output: None }
} else {
// Used for creating a redeem script for the new funding txo, since the funding pubkeys
// are unknown at this point. Only needed when selecting which UTXOs to include in the
// funding tx that would be sufficient to pay for fees. Hence, the value doesn't matter.
let dummy_pubkey = PublicKey::from_slice(&[2; 33]).unwrap();
let shared_output = bitcoin::TxOut {
value: shared_input
.as_ref()
.map(|shared_input| shared_input.previous_utxo.value)
.unwrap_or(Amount::ZERO)
.checked_add(value_added)
.ok_or(FundingContributionError::InvalidSpliceValue)?
.checked_sub(value_removed)
.ok_or(FundingContributionError::InvalidSpliceValue)?,
script_pubkey: make_funding_redeemscript(&dummy_pubkey, &dummy_pubkey).to_p2wsh(),
};
let claim_id = None;
let must_spend = shared_input.map(|input| vec![input]).unwrap_or_default();
if outputs.is_empty() {
let must_pay_to = &[shared_output];
$wallet.select_confirmed_utxos(claim_id, must_spend, must_pay_to, feerate.to_sat_per_kwu() as u32, u64::MAX)$(.$await)*.map_err(|_| FundingContributionError::CoinSelectionFailed)?
} else {
let must_pay_to: Vec<_> = outputs.iter().cloned().chain(core::iter::once(shared_output)).collect();
$wallet.select_confirmed_utxos(claim_id, must_spend, &must_pay_to, feerate.to_sat_per_kwu() as u32, u64::MAX)$(.$await)*.map_err(|_| FundingContributionError::CoinSelectionFailed)?
}
};
// NOTE: Must NOT fail after UTXO selection
let CoinSelection { confirmed_utxos: inputs, change_output } = coin_selection;
// The caller creating a FundingContribution is always the initiator for fee estimation
// purposes — this is conservative, overestimating rather than underestimating fees if
// the node ends up as the acceptor.
let estimated_fee = estimate_transaction_fee(&inputs, &outputs, change_output.as_ref(), true, is_splice, feerate);
debug_assert!(estimated_fee <= Amount::MAX_MONEY);
let contribution = FundingContribution {
value_added,
estimated_fee,
inputs,
outputs,
change_output,
feerate,
max_feerate,
is_splice,
};
Ok(contribution)
}};
}
impl FundingTemplate {
/// Creates a [`FundingContribution`] for adding funds to a channel using `wallet` to perform
/// coin selection.
///
/// `value_added` is the total amount to add to the channel for this contribution. When
/// replacing a prior contribution via RBF, use [`FundingTemplate::prior_contribution`] to
/// inspect the prior parameters. To add funds on top of the prior contribution's amount,
/// combine them: `prior.value_added() + additional_amount`.
pub async fn splice_in<W: CoinSelectionSource + MaybeSend>(
self, value_added: Amount, min_feerate: FeeRate, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if value_added == Amount::ZERO {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(value_added, vec![], shared_input, min_rbf_feerate, min_feerate, max_feerate, false, wallet, await)
}
/// Creates a [`FundingContribution`] for adding funds to a channel using `wallet` to perform
/// coin selection.
///
/// See [`FundingTemplate::splice_in`] for details.
pub fn splice_in_sync<W: CoinSelectionSourceSync>(
self, value_added: Amount, min_feerate: FeeRate, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if value_added == Amount::ZERO {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(
value_added,
vec![],
shared_input,
min_rbf_feerate,
min_feerate,
max_feerate,
false,
wallet,
)
}
/// Creates a [`FundingContribution`] for removing funds from a channel using `wallet` to
/// perform coin selection.
///
/// `outputs` are the complete set of withdrawal outputs for this contribution. When
/// replacing a prior contribution via RBF, use [`FundingTemplate::prior_contribution`] to
/// inspect the prior parameters. To keep existing withdrawals and add new ones, include the
/// prior's outputs: combine [`FundingContribution::outputs`] with the new outputs.
pub async fn splice_out<W: CoinSelectionSource + MaybeSend>(
self, outputs: Vec<TxOut>, min_feerate: FeeRate, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if outputs.is_empty() {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(Amount::ZERO, outputs, shared_input, min_rbf_feerate, min_feerate, max_feerate, false, wallet, await)
}
/// Creates a [`FundingContribution`] for removing funds from a channel using `wallet` to
/// perform coin selection.
///
/// See [`FundingTemplate::splice_out`] for details.
pub fn splice_out_sync<W: CoinSelectionSourceSync>(
self, outputs: Vec<TxOut>, min_feerate: FeeRate, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if outputs.is_empty() {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(
Amount::ZERO,
outputs,
shared_input,
min_rbf_feerate,
min_feerate,
max_feerate,
false,
wallet,
)
}
/// Creates a [`FundingContribution`] for both adding and removing funds from a channel using
/// `wallet` to perform coin selection.
///
/// `value_added` and `outputs` are the complete parameters for this contribution, not
/// increments on top of a prior contribution. When replacing a prior contribution via RBF,
/// use [`FundingTemplate::prior_contribution`] to inspect the prior parameters and combine
/// them as needed.
pub async fn splice_in_and_out<W: CoinSelectionSource + MaybeSend>(
self, value_added: Amount, outputs: Vec<TxOut>, min_feerate: FeeRate, max_feerate: FeeRate,
wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if value_added == Amount::ZERO && outputs.is_empty() {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(value_added, outputs, shared_input, min_rbf_feerate, min_feerate, max_feerate, false, wallet, await)
}
/// Creates a [`FundingContribution`] for both adding and removing funds from a channel using
/// `wallet` to perform coin selection.
///
/// See [`FundingTemplate::splice_in_and_out`] for details.
pub fn splice_in_and_out_sync<W: CoinSelectionSourceSync>(
self, value_added: Amount, outputs: Vec<TxOut>, min_feerate: FeeRate, max_feerate: FeeRate,
wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
if value_added == Amount::ZERO && outputs.is_empty() {
return Err(FundingContributionError::InvalidSpliceValue);
}
let FundingTemplate { shared_input, min_rbf_feerate, .. } = self;
build_funding_contribution!(
value_added,
outputs,
shared_input,
min_rbf_feerate,
min_feerate,
max_feerate,
false,
wallet,
)
}
/// Creates a [`FundingContribution`] for an RBF (Replace-By-Fee) attempt on a pending splice.
///
/// `max_feerate` is the maximum feerate the caller is willing to accept as acceptor. It is
/// used as the returned contribution's `max_feerate` and also constrains coin selection when
/// re-running it for prior contributions that cannot be adjusted or fee-bump-only
/// contributions.
///
/// This handles the prior contribution logic internally:
/// - If the prior contribution's feerate can be adjusted to the minimum RBF feerate, the
/// adjusted contribution is returned directly. For splice-in, the change output absorbs
/// the fee difference. For splice-out (no wallet inputs), the holder's channel balance
/// covers the higher fees.
/// - If adjustment fails, coin selection is re-run using the prior contribution's
/// parameters and the caller's `max_feerate`. For splice-out contributions, this changes
/// the fee source: wallet inputs are selected to cover fees instead of deducting them
/// from the channel balance.
/// - If no prior contribution exists, coin selection is run for a fee-bump-only contribution
/// (`value_added = 0`), covering fees for the common fields and shared input/output via
/// a newly selected input. Check [`FundingTemplate::prior_contribution`] to see if this
/// is intended.
///
/// # Errors
///
/// Returns a [`FundingContributionError`] if this is not an RBF scenario, if `max_feerate`
/// is below the minimum RBF feerate, or if coin selection fails.
pub async fn rbf<W: CoinSelectionSource + MaybeSend>(
self, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
let FundingTemplate { shared_input, min_rbf_feerate, prior_contribution } = self;
let rbf_feerate = min_rbf_feerate.ok_or(FundingContributionError::NotRbfScenario)?;
if rbf_feerate > max_feerate {
return Err(FundingContributionError::FeeRateExceedsMaximum {
feerate: rbf_feerate,
max_feerate,
});
}
match prior_contribution {
Some(PriorContribution { contribution, holder_balance }) => {
// Try to adjust the prior contribution to the RBF feerate. This fails if
// the holder balance can't cover the adjustment (splice-out) or the fee
// buffer is insufficient (splice-in), or if the prior's feerate is already
// above rbf_feerate (e.g., from a counterparty-initiated RBF that locked
// at a higher feerate). In all cases, fall through to re-run coin selection.
if let Some(holder_balance) = holder_balance {
if contribution
.net_value_for_initiator_at_feerate(rbf_feerate, holder_balance)
.is_ok()
{
let mut adjusted = contribution
.for_initiator_at_feerate(rbf_feerate, holder_balance)
.expect("feerate compatibility already checked");
adjusted.max_feerate = max_feerate;
return Ok(adjusted);
}
}
build_funding_contribution!(contribution.value_added, contribution.outputs, shared_input, min_rbf_feerate, rbf_feerate, max_feerate, true, wallet, await)
},
None => {
build_funding_contribution!(Amount::ZERO, vec![], shared_input, min_rbf_feerate, rbf_feerate, max_feerate, true, wallet, await)
},
}
}
/// Creates a [`FundingContribution`] for an RBF (Replace-By-Fee) attempt on a pending splice.
///
/// See [`FundingTemplate::rbf`] for details.
pub fn rbf_sync<W: CoinSelectionSourceSync>(
self, max_feerate: FeeRate, wallet: W,
) -> Result<FundingContribution, FundingContributionError> {
let FundingTemplate { shared_input, min_rbf_feerate, prior_contribution } = self;
let rbf_feerate = min_rbf_feerate.ok_or(FundingContributionError::NotRbfScenario)?;
if rbf_feerate > max_feerate {
return Err(FundingContributionError::FeeRateExceedsMaximum {
feerate: rbf_feerate,
max_feerate,
});
}
match prior_contribution {
Some(PriorContribution { contribution, holder_balance }) => {
// See comment in `rbf` for details on when this adjustment fails.
if let Some(holder_balance) = holder_balance {
if contribution
.net_value_for_initiator_at_feerate(rbf_feerate, holder_balance)
.is_ok()
{
let mut adjusted = contribution
.for_initiator_at_feerate(rbf_feerate, holder_balance)
.expect("feerate compatibility already checked");
adjusted.max_feerate = max_feerate;
return Ok(adjusted);
}
}
build_funding_contribution!(
contribution.value_added,
contribution.outputs,
shared_input,
min_rbf_feerate,
rbf_feerate,
max_feerate,
true,
wallet,
)
},
None => {
build_funding_contribution!(
Amount::ZERO,
vec![],
shared_input,
min_rbf_feerate,
rbf_feerate,
max_feerate,
true,
wallet,
)
},
}
}
}
fn estimate_transaction_fee(
inputs: &[FundingTxInput], outputs: &[TxOut], change_output: Option<&TxOut>,
is_initiator: bool, is_splice: bool, feerate: FeeRate,
) -> Amount {
let input_weight: u64 = inputs
.iter()
.map(|input| BASE_INPUT_WEIGHT.saturating_add(input.utxo.satisfaction_weight))
.fold(0, |total_weight, input_weight| total_weight.saturating_add(input_weight));
let output_weight: u64 = outputs
.iter()
.chain(change_output.into_iter())
.map(|txout| txout.weight().to_wu())
.fold(0, |total_weight, output_weight| total_weight.saturating_add(output_weight));
let mut weight = input_weight.saturating_add(output_weight);
// The initiator pays for all common fields and the shared output in the funding transaction.
if is_initiator {
weight = weight
.saturating_add(TX_COMMON_FIELDS_WEIGHT)
// The weight of the funding output, a P2WSH output
// NOTE: The witness script hash given here is irrelevant as it's a fixed size and we just want
// to calculate the contributed weight, so we use an all-zero hash.
//
// TODO(taproot): Needs to consider different weights based on channel type
.saturating_add(
get_output_weight(&ScriptBuf::new_p2wsh(&WScriptHash::from_raw_hash(
Hash::all_zeros(),
)))
.to_wu(),
);
// The splice initiator pays for the input spending the previous funding output.
if is_splice {
weight = weight
.saturating_add(BASE_INPUT_WEIGHT)
.saturating_add(EMPTY_SCRIPT_SIG_WEIGHT)
.saturating_add(FUNDING_TRANSACTION_WITNESS_WEIGHT);
#[cfg(feature = "grind_signatures")]
{
// Guarantees a low R signature
weight -= 1;
}
}
}
Weight::from_wu(weight) * feerate
}
/// The components of a funding transaction contributed by one party.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FundingContribution {
/// The amount to contribute to the channel.
///
/// If `value_added` is [`Amount::ZERO`], then any fees will be deducted from the channel
/// balance instead of paid by `inputs`.
value_added: Amount,
/// The estimate fees responsible to be paid for the contribution.
estimated_fee: Amount,
/// The inputs included in the funding transaction to meet the contributed amount plus fees. Any
/// excess amount will be sent to a change output.
inputs: Vec<FundingTxInput>,
/// The outputs to include in the funding transaction. The total value of all outputs plus fees
/// will be the amount that is removed.
outputs: Vec<TxOut>,
/// The output where any change will be sent.
change_output: Option<TxOut>,
/// The fee rate used to select `inputs` (the minimum feerate).
feerate: FeeRate,
/// The maximum fee rate to accept as acceptor before rejecting the splice.
max_feerate: FeeRate,
/// Whether the contribution is for funding a splice.
is_splice: bool,
}
impl_writeable_tlv_based!(FundingContribution, {
(1, value_added, required),
(3, estimated_fee, required),
(5, inputs, optional_vec),
(7, outputs, optional_vec),
(9, change_output, option),
(11, feerate, required),
(13, max_feerate, required),
(15, is_splice, required),
});
impl FundingContribution {
pub(super) fn feerate(&self) -> FeeRate {
self.feerate
}
pub(super) fn is_splice(&self) -> bool {
self.is_splice
}
pub(super) fn contributed_inputs(&self) -> impl Iterator<Item = OutPoint> + '_ {
self.inputs.iter().map(|input| input.utxo.outpoint)
}
pub(super) fn contributed_outputs(&self) -> impl Iterator<Item = &TxOut> + '_ {
self.outputs.iter().chain(self.change_output.iter())
}
/// Returns the amount added to the channel by this contribution.
pub fn value_added(&self) -> Amount {
self.value_added
}
/// Returns the outputs (e.g., withdrawal destinations) included in this contribution.
///
/// This does not include the change output; see [`FundingContribution::change_output`].
pub fn outputs(&self) -> &[TxOut] {
&self.outputs
}
/// Returns the change output included in this contribution, if any.
///
/// When coin selection provides more value than needed for the funding contribution and fees,
/// the surplus is returned to the wallet via this change output.
pub fn change_output(&self) -> Option<&TxOut> {
self.change_output.as_ref()
}
pub(super) fn into_tx_parts(self) -> (Vec<FundingTxInput>, Vec<TxOut>) {
let FundingContribution { inputs, mut outputs, change_output, .. } = self;
if let Some(change_output) = change_output {
outputs.push(change_output);
}
(inputs, outputs)
}
pub(super) fn into_contributed_inputs_and_outputs(self) -> (Vec<OutPoint>, Vec<TxOut>) {
let (inputs, outputs) = self.into_tx_parts();
(inputs.into_iter().map(|input| input.utxo.outpoint).collect(), outputs)
}
pub(super) fn into_unique_contributions<'a>(
self, existing_inputs: impl Iterator<Item = OutPoint>,
existing_outputs: impl Iterator<Item = &'a TxOut>,
) -> Option<(Vec<OutPoint>, Vec<TxOut>)> {
let (mut inputs, mut outputs) = self.into_contributed_inputs_and_outputs();
for existing in existing_inputs {
inputs.retain(|input| *input != existing);
}
for existing in existing_outputs {
outputs.retain(|output| *output != *existing);
}
if inputs.is_empty() && outputs.is_empty() {
None
} else {
Some((inputs, outputs))
}
}
/// Validates that the funding inputs are suitable for use in the interactive transaction
/// protocol, checking prevtx sizes and input sufficiency.
pub fn validate(&self) -> Result<(), String> {
for FundingTxInput { utxo, prevtx, .. } in self.inputs.iter() {
use crate::util::ser::Writeable;
const MESSAGE_TEMPLATE: msgs::TxAddInput = msgs::TxAddInput {
channel_id: ChannelId([0; 32]),
serial_id: 0,
prevtx: None,
prevtx_out: 0,
sequence: 0,
// Mutually exclusive with prevtx, which is accounted for below.
shared_input_txid: None,
};
let message_len = MESSAGE_TEMPLATE.serialized_length() + prevtx.serialized_length();
if message_len > LN_MAX_MSG_LEN {
return Err(format!(
"Funding input references a prevtx that is too large for tx_add_input: {}",
utxo.outpoint
));
}
}
// Fees for splice-out are paid from the channel balance whereas fees for splice-in
// are paid by the funding inputs. Therefore, in the case of splice-out, we add the
// fees on top of the user-specified contribution. We leave the user-specified
// contribution as-is for splice-ins.
if !self.inputs.is_empty() {
let mut total_input_value = Amount::ZERO;
for FundingTxInput { utxo, .. } in self.inputs.iter() {
total_input_value = total_input_value
.checked_add(utxo.output.value)
.ok_or("Sum of input values is greater than the total bitcoin supply")?;
}
// If the inputs are enough to cover intended contribution amount plus fees (which
// include the change output weight when present), we are fine.
// If the inputs are less, but enough to cover intended contribution amount with
// (lower) fees without change, we are also fine (change will not be generated).
// Since estimated_fee includes change weight, this check is conservative.
//
// Note: dust limit is not relevant in this check.
let contributed_input_value = self.value_added;
let estimated_fee = self.estimated_fee;
let minimal_input_amount_needed = contributed_input_value
.checked_add(estimated_fee)
.ok_or(format!("{contributed_input_value} contribution plus {estimated_fee} fee estimate exceeds the total bitcoin supply"))?;
if total_input_value < minimal_input_amount_needed {
return Err(format!(
"Total input amount {total_input_value} is lower than needed for splice-in contribution {contributed_input_value}, considering fees of {estimated_fee}. Need more inputs.",
));
}
}
Ok(())
}
/// Computes the adjusted fee and change output value at the given target feerate, which may
/// differ from the feerate used during coin selection.
///
/// The `is_initiator` parameter determines fee responsibility: the initiator pays for common
/// transaction fields, the shared input, and the shared output, while the acceptor only pays
/// for their own contributed inputs and outputs.
///
/// On success, returns the new estimated fee and, if applicable, the new change output value:
/// - `Some(change)` — the adjusted change output value
/// - `None` — no change output (no inputs or change fell below dust)
///
/// Returns `Err` if the contribution cannot accommodate the target feerate.
fn compute_feerate_adjustment(
&self, target_feerate: FeeRate, holder_balance: Amount, is_initiator: bool,
) -> Result<(Amount, Option<Amount>), FeeRateAdjustmentError> {
if target_feerate < self.feerate {
return Err(FeeRateAdjustmentError::FeeRateTooLow {
target_feerate,
min_feerate: self.feerate,
});
}
// If the target fee rate exceeds our max fee rate, we may still add our contribution
// if we pay less in fees at the target feerate than at the original feerate. This can
// happen when adjusting as acceptor, since the acceptor doesn't pay for common fields
// and the shared input / output.
if target_feerate > self.max_feerate {
let target_fee = estimate_transaction_fee(
&self.inputs,
&self.outputs,
self.change_output.as_ref(),
is_initiator,
self.is_splice,
target_feerate,
);
if target_fee > self.estimated_fee {
return Err(FeeRateAdjustmentError::FeeRateTooHigh {
target_feerate,
max_feerate: self.max_feerate,
target_fee,
original_fee: self.estimated_fee,
});
}
}
if !self.inputs.is_empty() {
if let Some(ref change_output) = self.change_output {
let old_change_value = change_output.value;
let dust_limit = change_output.script_pubkey.minimal_non_dust();
// Target fee including the change output's weight.
let target_fee = estimate_transaction_fee(
&self.inputs,
&self.outputs,
self.change_output.as_ref(),
is_initiator,
self.is_splice,
target_feerate,
);
let fee_buffer = self
.estimated_fee
.checked_add(old_change_value)
.ok_or(FeeRateAdjustmentError::FeeBufferOverflow)?;
match fee_buffer.checked_sub(target_fee) {
Some(new_change_value) if new_change_value >= dust_limit => {
Ok((target_fee, Some(new_change_value)))
},
_ => {
// Change would be below dust or negative. Try without change.
let target_fee_no_change = estimate_transaction_fee(
&self.inputs,
&self.outputs,
None,
is_initiator,
self.is_splice,
target_feerate,
);
if target_fee_no_change > fee_buffer {
Err(FeeRateAdjustmentError::FeeBufferInsufficient {
source: "estimated fee + change value",
available: fee_buffer,
required: target_fee_no_change,
})
} else {
Ok((target_fee_no_change, None))
}
},
}
} else {
// No change output.
let target_fee = estimate_transaction_fee(
&self.inputs,
&self.outputs,
None,
is_initiator,
self.is_splice,
target_feerate,
);
// The fee buffer is total input value minus value_added and output values.
// This is estimated_fee plus the coin selection surplus (dust burned to
// fees), ensuring we never silently reduce value_added beyond the small
// surplus from coin selection.
let total_input_value: Amount =
self.inputs.iter().map(|i| i.utxo.output.value).sum();
let output_values: Amount = self.outputs.iter().map(|o| o.value).sum();
let fee_buffer = total_input_value
.checked_sub(self.value_added)
.and_then(|v| v.checked_sub(output_values))
.ok_or(FeeRateAdjustmentError::FeeBufferOverflow)?;
if target_fee > fee_buffer {
return Err(FeeRateAdjustmentError::FeeBufferInsufficient {
source: "estimated fee + coin selection surplus",
available: fee_buffer,
required: target_fee,
});
}
Ok((target_fee, None))
}
} else {
// No inputs (splice-out): fees paid from channel balance.
let target_fee = estimate_transaction_fee(
&[],
&self.outputs,
None,
is_initiator,
self.is_splice,
target_feerate,
);
// Check that the channel balance can cover the withdrawal outputs plus fees.
let value_removed: Amount = self.outputs.iter().map(|o| o.value).sum();
let total_cost = target_fee
.checked_add(value_removed)
.ok_or(FeeRateAdjustmentError::FeeBufferOverflow)?;
if total_cost > holder_balance {
return Err(FeeRateAdjustmentError::FeeBufferInsufficient {
source: "channel balance - withdrawal outputs",
available: holder_balance.checked_sub(value_removed).unwrap_or(Amount::ZERO),
required: target_fee,
});
}
// Surplus goes back to the channel balance.
Ok((target_fee, None))
}
}
/// Adjusts the contribution for a different feerate, updating the change output, fee
/// estimate, and feerate. Returns the adjusted contribution, or an error if the feerate
/// can't be accommodated.
fn at_feerate(
mut self, feerate: FeeRate, holder_balance: Amount, is_initiator: bool,
) -> Result<Self, FeeRateAdjustmentError> {
let (new_estimated_fee, new_change) =
self.compute_feerate_adjustment(feerate, holder_balance, is_initiator)?;
let surplus = self.fee_buffer_surplus(new_estimated_fee, &new_change);
match new_change {
Some(value) => self.change_output.as_mut().unwrap().value = value,
None => self.change_output = None,