lightning 0.3.0-beta1

A Complete Bitcoin Lightning Library in Rust. Handles the core functionality of the Lightning Network, allowing clients to implement custom wallet, chain interactions, storage and network logic without enforcing a specific runtime.
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
//! Defines the `TxBuilder` trait, and the `SpecTxBuilder` type

use core::cmp;

use bitcoin::secp256k1::{self, PublicKey, Secp256k1};

use crate::ln::chan_utils::{
	commit_tx_fee_sat, htlc_success_tx_weight, htlc_timeout_tx_weight, htlc_tx_fees_sat,
	second_stage_tx_fees_sat, ChannelTransactionParameters, CommitmentTransaction,
	HTLCOutputInCommitment,
};
use crate::ln::channel::{
	get_v2_channel_reserve_satoshis, CommitmentStats, ANCHOR_OUTPUT_VALUE_SATOSHI,
	FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE, MIN_CHANNEL_VALUE_SATOSHIS,
};
use crate::prelude::*;
use crate::types::features::ChannelTypeFeatures;
use crate::util::logger::Logger;

pub(crate) struct HTLCAmountDirection {
	pub outbound: bool,
	pub amount_msat: u64,
}

impl HTLCAmountDirection {
	fn is_dust(
		&self, local: bool, feerate_per_kw: u32, broadcaster_dust_limit_satoshis: u64,
		channel_type: &ChannelTypeFeatures,
	) -> bool {
		let (success_tx_fee_sat, timeout_tx_fee_sat) =
			second_stage_tx_fees_sat(channel_type, feerate_per_kw);
		let htlc_tx_fee_sat =
			if self.outbound == local { timeout_tx_fee_sat } else { success_tx_fee_sat };
		self.amount_msat / 1000 < broadcaster_dust_limit_satoshis + htlc_tx_fee_sat
	}
}

pub(crate) struct NextCommitmentStats {
	pub holder_balance_msat: u64,
	pub counterparty_balance_msat: u64,
	pub dust_exposure_msat: u64,
	#[cfg(any(test, fuzzing))]
	pub nondust_htlc_count: usize,
	#[cfg(any(test, fuzzing))]
	pub commit_tx_fee_sat: u64,
}

pub(crate) struct ChannelStats {
	pub commitment_stats: NextCommitmentStats,
	pub available_balances: crate::ln::channel::AvailableBalances,
}

fn commit_plus_htlc_tx_fees_msat(
	local: bool, next_commitment_htlcs: &[HTLCAmountDirection], dust_buffer_feerate: u32,
	feerate: u32, broadcaster_dust_limit_satoshis: u64, channel_type: &ChannelTypeFeatures,
) -> (u64, u64) {
	let accepted_nondust_htlcs = next_commitment_htlcs
		.iter()
		.filter(|htlc| {
			htlc.outbound != local
				&& !htlc.is_dust(
					local,
					dust_buffer_feerate,
					broadcaster_dust_limit_satoshis,
					channel_type,
				)
		})
		.count();
	let offered_nondust_htlcs = next_commitment_htlcs
		.iter()
		.filter(|htlc| {
			htlc.outbound == local
				&& !htlc.is_dust(
					local,
					dust_buffer_feerate,
					broadcaster_dust_limit_satoshis,
					channel_type,
				)
		})
		.count();

	let commitment_fee_sat =
		commit_tx_fee_sat(feerate, accepted_nondust_htlcs + offered_nondust_htlcs, channel_type);
	let second_stage_fees_sat =
		htlc_tx_fees_sat(feerate, accepted_nondust_htlcs, offered_nondust_htlcs, channel_type);
	let total_fees_msat = (commitment_fee_sat + second_stage_fees_sat) * 1000;

	let extra_accepted_htlc_commitment_fee_sat = commit_tx_fee_sat(
		feerate,
		accepted_nondust_htlcs + 1 + offered_nondust_htlcs,
		channel_type,
	);
	let extra_accepted_htlc_second_stage_fees_sat =
		htlc_tx_fees_sat(feerate, accepted_nondust_htlcs + 1, offered_nondust_htlcs, channel_type);
	let extra_accepted_htlc_total_fees_msat =
		(extra_accepted_htlc_commitment_fee_sat + extra_accepted_htlc_second_stage_fees_sat) * 1000;

	(total_fees_msat, extra_accepted_htlc_total_fees_msat)
}

fn total_anchors_sat(channel_type: &ChannelTypeFeatures) -> u64 {
	if channel_type.supports_anchors_zero_fee_htlc_tx() {
		ANCHOR_OUTPUT_VALUE_SATOSHI * 2
	} else {
		0
	}
}

fn checked_sub_from_funder(
	is_outbound_from_holder: bool, value_to_holder: u64, value_to_counterparty: u64,
	value_to_subtract: u64,
) -> Result<(u64, u64), ()> {
	if is_outbound_from_holder {
		Ok((value_to_holder.checked_sub(value_to_subtract).ok_or(())?, value_to_counterparty))
	} else {
		Ok((value_to_holder, value_to_counterparty.checked_sub(value_to_subtract).ok_or(())?))
	}
}

fn saturating_sub_from_funder(
	is_outbound_from_holder: bool, value_to_holder: u64, value_to_counterparty: u64,
	value_to_subtract: u64,
) -> (u64, u64) {
	if is_outbound_from_holder {
		(value_to_holder.saturating_sub(value_to_subtract), value_to_counterparty)
	} else {
		(value_to_holder, value_to_counterparty.saturating_sub(value_to_subtract))
	}
}

fn get_dust_buffer_feerate(feerate_per_kw: u32) -> u32 {
	// When calculating our exposure to dust HTLCs, we assume that the channel feerate
	// may, at any point, increase by at least 10 sat/vB (i.e 2530 sat/kWU) or 25%,
	// whichever is higher. This ensures that we aren't suddenly exposed to significantly
	// more dust balance if the feerate increases when we have several HTLCs pending
	// which are near the dust limit.
	let feerate_plus_quarter = feerate_per_kw.checked_mul(1250).map(|v| v / 1000);
	cmp::max(feerate_per_kw.saturating_add(2530), feerate_plus_quarter.unwrap_or(u32::MAX))
}

#[derive(Clone, Copy, Debug)]
pub(crate) struct ChannelConstraints {
	pub holder_dust_limit_satoshis: u64,
	pub counterparty_selected_channel_reserve_satoshis: u64,
	pub counterparty_dust_limit_satoshis: u64,
	pub holder_selected_channel_reserve_satoshis: u64,
	pub counterparty_htlc_minimum_msat: u64,
	pub counterparty_max_htlc_value_in_flight_msat: u64,
	pub counterparty_max_accepted_htlcs: u64,
}

fn get_dust_exposure_stats(
	local: bool, commitment_htlcs: &[HTLCAmountDirection], feerate_per_kw: u32,
	dust_exposure_limiting_feerate: Option<u32>, broadcaster_dust_limit_satoshis: u64,
	channel_type: &ChannelTypeFeatures,
) -> (u64, Option<u64>) {
	let excess_feerate =
		feerate_per_kw.saturating_sub(dust_exposure_limiting_feerate.unwrap_or(feerate_per_kw));
	if channel_type.supports_anchor_zero_fee_commitments() {
		debug_assert_eq!(feerate_per_kw, 0);
		debug_assert_eq!(excess_feerate, 0);
	}

	// Increment the feerate by a buffer to calculate dust exposure
	let dust_buffer_feerate = get_dust_buffer_feerate(feerate_per_kw);

	// Calculate dust exposure on commitment transaction
	let dust_exposure_msat = commitment_htlcs
		.iter()
		.filter_map(|htlc| {
			htlc.is_dust(local, dust_buffer_feerate, broadcaster_dust_limit_satoshis, channel_type)
				.then_some(htlc.amount_msat)
		})
		.sum();

	if local || excess_feerate == 0 {
		(dust_exposure_msat, None)
	} else {
		// Add any excess fees to dust exposure on counterparty transactions
		let (excess_fees_msat, extra_accepted_htlc_excess_fees_msat) =
			commit_plus_htlc_tx_fees_msat(
				local,
				&commitment_htlcs,
				dust_buffer_feerate,
				excess_feerate,
				broadcaster_dust_limit_satoshis,
				channel_type,
			);
		(
			dust_exposure_msat + excess_fees_msat,
			Some(dust_exposure_msat + extra_accepted_htlc_excess_fees_msat),
		)
	}
}

fn has_output(
	is_outbound_from_holder: bool, holder_balance_before_fee_msat: u64,
	counterparty_balance_before_fee_msat: u64, feerate_per_kw: u32, nondust_htlc_count: usize,
	broadcaster_dust_limit_satoshis: u64, channel_type: &ChannelTypeFeatures,
) -> bool {
	let commit_tx_fee_sat = commit_tx_fee_sat(feerate_per_kw, nondust_htlc_count, channel_type);
	let (holder_balance_msat, counterparty_balance_msat) = saturating_sub_from_funder(
		is_outbound_from_holder,
		holder_balance_before_fee_msat,
		counterparty_balance_before_fee_msat,
		commit_tx_fee_sat.saturating_mul(1000),
	);

	// Make sure the commitment transaction has at least one output
	let dust_limit_msat = broadcaster_dust_limit_satoshis * 1000;
	let has_no_output = holder_balance_msat < dust_limit_msat
		&& counterparty_balance_msat < dust_limit_msat
		&& nondust_htlc_count == 0
		// 0FC channels always have a P2A output on the commitment transaction
		&& !channel_type.supports_anchor_zero_fee_commitments();
	!has_no_output
}

fn get_next_commitment_stats(
	local: bool, is_outbound_from_holder: bool, channel_value_satoshis: u64,
	value_to_holder_msat: u64, next_commitment_htlcs: &[HTLCAmountDirection],
	addl_nondust_htlc_count: usize, feerate_per_kw: u32, assume_fee_spike: bool,
	dust_exposure_limiting_feerate: Option<u32>, broadcaster_dust_limit_satoshis: u64,
	channel_type: &ChannelTypeFeatures,
) -> Result<NextCommitmentStats, ()> {
	if channel_type.supports_anchor_zero_fee_commitments() {
		debug_assert_eq!(feerate_per_kw, 0);
	}

	// Calculate balances after htlcs
	let value_to_counterparty_msat =
		(channel_value_satoshis * 1000).checked_sub(value_to_holder_msat).ok_or(())?;
	let outbound_htlcs_value_msat: u64 = next_commitment_htlcs
		.iter()
		.filter_map(|htlc| htlc.outbound.then_some(htlc.amount_msat))
		.sum();
	let inbound_htlcs_value_msat: u64 = next_commitment_htlcs
		.iter()
		.filter_map(|htlc| (!htlc.outbound).then_some(htlc.amount_msat))
		.sum();
	let value_to_holder_after_htlcs_msat =
		value_to_holder_msat.checked_sub(outbound_htlcs_value_msat).ok_or(())?;
	let value_to_counterparty_after_htlcs_msat =
		value_to_counterparty_msat.checked_sub(inbound_htlcs_value_msat).ok_or(())?;

	// Subtract the anchors from the channel funder

	// We MUST use checked subs here, as the funder's balance is not guaranteed to be greater
	// than or equal to `total_anchors_sat`.
	//
	// This is because when the remote party sends an `update_fee` message, we build the new
	// commitment transaction *before* checking whether the remote party's balance is enough to
	// cover the total anchor sum.

	let total_anchors_sat = total_anchors_sat(channel_type);
	let (holder_balance_before_fee_msat, counterparty_balance_before_fee_msat) =
		checked_sub_from_funder(
			is_outbound_from_holder,
			value_to_holder_after_htlcs_msat,
			value_to_counterparty_after_htlcs_msat,
			total_anchors_sat.saturating_mul(1000),
		)?;

	let (dust_exposure_msat, _extra_accepted_htlc_dust_exposure_msat) = get_dust_exposure_stats(
		local,
		next_commitment_htlcs,
		feerate_per_kw,
		dust_exposure_limiting_feerate,
		broadcaster_dust_limit_satoshis,
		channel_type,
	);

	let spiked_feerate = if assume_fee_spike && !channel_type.supports_anchors_zero_fee_htlc_tx() {
		feerate_per_kw.saturating_mul(FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32)
	} else {
		feerate_per_kw
	};

	let spiked_nondust_htlc_count = next_commitment_htlcs
		.iter()
		.filter(|htlc| {
			!htlc.is_dust(local, spiked_feerate, broadcaster_dust_limit_satoshis, channel_type)
		})
		.count();

	// For zero-reserve channels, we check two things independently:
	// 1) Given the current set of HTLCs and feerate, does the commitment have at least one output ?
	//
	// We only assume fee spikes in legacy channels, and we do not allow
	// `holder_selected_channel_reserve_satoshis` to be set to zero in such channels. It is
	// nonetheless still possible to reach the no-outputs case in a fee spike with solely the
	// counterparty selected reserve set to zero, so we still guard against this case here.
	//
	// We don't guard against no-outputs under fee spikes further below in
	// `get_available_balances`; in the worst case, the receiver of the HTLC we just sent fails
	// it back.
	if !has_output(
		is_outbound_from_holder,
		holder_balance_before_fee_msat,
		counterparty_balance_before_fee_msat,
		spiked_feerate,
		spiked_nondust_htlc_count,
		broadcaster_dust_limit_satoshis,
		channel_type,
	) {
		return Err(());
	}

	// 2) Now including any additional non-dust HTLCs (usually the fee spike buffer HTLC), does the funder cover
	// this bigger transaction fee ? The funder can dip below their dust limit to cover this case, as the
	// commitment will have at least one output: the non-dust fee spike buffer HTLC offered by the counterparty.
	let nondust_htlc_count = next_commitment_htlcs
		.iter()
		.filter(|htlc| {
			!htlc.is_dust(local, feerate_per_kw, broadcaster_dust_limit_satoshis, channel_type)
		})
		.count();
	// Note here we use the htlc count at the current feerate together with the spiked feerate;
	// this makes sure that the holder can afford any fee bump between 1x to 2x from the current
	// feerate if the fee spike multiple is included.
	let commit_tx_fee_sat = commit_tx_fee_sat(
		spiked_feerate,
		nondust_htlc_count + addl_nondust_htlc_count,
		channel_type,
	);
	let (holder_balance_msat, counterparty_balance_msat) = checked_sub_from_funder(
		is_outbound_from_holder,
		holder_balance_before_fee_msat,
		counterparty_balance_before_fee_msat,
		commit_tx_fee_sat.saturating_mul(1000),
	)?;

	Ok(NextCommitmentStats {
		holder_balance_msat,
		counterparty_balance_msat,
		dust_exposure_msat,
		#[cfg(any(test, fuzzing))]
		nondust_htlc_count: nondust_htlc_count + addl_nondust_htlc_count,
		#[cfg(any(test, fuzzing))]
		commit_tx_fee_sat,
	})
}

/// Determines the maximum value that the holder can splice out of the channel, accounting
/// for the updated reserves after said splice. This maximum also makes sure the local commitment
/// retains at least one output after the splice, which is particularly relevant for
/// zero-reserve channels.
//
// The equation to determine `max_splice_percentage_constraint_sat` is:
// 1) floor((c - s) / 100) == h - s - d
// We want the maximum value of s that will satisfy equation 1, therefore, we solve:
// 2) (c - s) / 100 < h - s - d + 1
// where c: `channel_value_satoshis`
//       s: `max_splice_percentage_constraint_sat`
//       h: `local_balance_before_fee_sat`
//       d: `post_splice_delta_above_reserve_sat`
// This results in:
// 3) s < (100h + 100 - 100d - c) / 99
fn get_next_splice_out_maximum_sat(
	is_outbound_from_holder: bool, channel_value_satoshis: u64, local_balance_before_fee_msat: u64,
	remote_balance_before_fee_msat: u64, local_nondust_htlc_count: usize,
	remote_nondust_htlc_count: usize, feerate_per_kw: u32, spiked_feerate: u32,
	channel_constraints: &ChannelConstraints, channel_type: &ChannelTypeFeatures,
) -> u64 {
	let post_splice_delta_above_reserve_sat = if is_outbound_from_holder {
		let nondust_htlc_count = cmp::max(local_nondust_htlc_count, remote_nondust_htlc_count);
		let commit_tx_fee_sat =
			commit_tx_fee_sat(spiked_feerate, nondust_htlc_count + 1, channel_type);
		commit_tx_fee_sat
	} else {
		0
	};
	let local_balance_before_fee_sat = local_balance_before_fee_msat / 1000;
	let mut next_splice_out_maximum_sat = if channel_constraints
		.counterparty_selected_channel_reserve_satoshis
		!= 0
	{
		let dividend_sat = local_balance_before_fee_sat
			.saturating_mul(100)
			.saturating_add(100)
			.saturating_sub(post_splice_delta_above_reserve_sat.saturating_mul(100))
			.saturating_sub(channel_value_satoshis);
		// Calculate the greatest integer that is strictly less than the RHS of inequality 3 above
		let max_splice_percentage_constraint_sat = dividend_sat.saturating_sub(1) / 99;
		let max_splice_dust_limit_constraint_sat = local_balance_before_fee_sat
			.saturating_sub(channel_constraints.holder_dust_limit_satoshis)
			.saturating_sub(post_splice_delta_above_reserve_sat);
		// Both constraints must be satisfied, so take the minimum of the two maximums
		let max_splice_out_sat =
			cmp::min(max_splice_percentage_constraint_sat, max_splice_dust_limit_constraint_sat);
		#[cfg(debug_assertions)]
		if max_splice_out_sat == 0 {
			let current_balance_sat =
				local_balance_before_fee_sat.saturating_sub(post_splice_delta_above_reserve_sat);
			let v2_reserve_sat = get_v2_channel_reserve_satoshis(
				channel_value_satoshis,
				channel_constraints.holder_dust_limit_satoshis,
				false,
			)
			.unwrap();
			// If the holder cannot splice out anything, they must be at or
			// below the v2 reserve
			debug_assert!(current_balance_sat <= v2_reserve_sat);
		} else {
			let post_splice_reserve_sat = get_v2_channel_reserve_satoshis(
				channel_value_satoshis.saturating_sub(max_splice_out_sat),
				channel_constraints.holder_dust_limit_satoshis,
				false,
			)
			.unwrap();
			// If the holder can splice out some maximum, splicing out that
			// maximum lands them at exactly the new v2 reserve + the
			// `post_splice_delta_above_reserve_sat`
			debug_assert_eq!(
				local_balance_before_fee_sat.saturating_sub(max_splice_out_sat),
				post_splice_reserve_sat.saturating_add(post_splice_delta_above_reserve_sat)
			);
			// Splice out an additional satoshi, and check that we are offside
			let offside_splice_out_sat = max_splice_out_sat + 1;
			let post_splice_reserve_sat_result = get_v2_channel_reserve_satoshis(
				channel_value_satoshis.saturating_sub(offside_splice_out_sat),
				channel_constraints.holder_dust_limit_satoshis,
				false,
			);
			match post_splice_reserve_sat_result {
				Ok(reserve) => debug_assert!(
					local_balance_before_fee_sat.saturating_sub(offside_splice_out_sat)
						< reserve.saturating_add(post_splice_delta_above_reserve_sat)
				),
				Err(()) => (),
			}
		}
		max_splice_out_sat
	} else {
		// In a zero-reserve channel, the holder is free to withdraw up to its `post_splice_delta_above_reserve_sat`.
		local_balance_before_fee_sat.saturating_sub(post_splice_delta_above_reserve_sat)
	};

	// If the current `next_splice_out_maximum_sat` would produce a local commitment with no
	// outputs, bump this maximum such that, after the splice, the holder's balance covers at
	// least `dust_limit_satoshis` and, if they are the funder, `current_tx_fee_sat`.
	// We don't include an additional non-dust inbound HTLC in the `current_tx_fee_sat`,
	// because we don't mind if the holder dips below their dust limit to cover the fee for that
	// inbound non-dust HTLC.
	//
	// We use the regular feerate instead of the spiked feerate here as zero-reserve is not
	// allowed on legacy channels.
	let current_tx_fee_sat = commit_tx_fee_sat(feerate_per_kw, 0, channel_type);
	let mut trim_splice_out_max_if_no_outputs = |nondust_htlc_count, dust_limit_satoshis| {
		if !has_output(
			is_outbound_from_holder,
			local_balance_before_fee_msat.saturating_sub(next_splice_out_maximum_sat * 1000),
			remote_balance_before_fee_msat,
			feerate_per_kw,
			nondust_htlc_count,
			dust_limit_satoshis,
			channel_type,
		) {
			let min_balance_sat = if is_outbound_from_holder {
				dust_limit_satoshis.saturating_add(current_tx_fee_sat)
			} else {
				dust_limit_satoshis
			};
			next_splice_out_maximum_sat =
				(local_balance_before_fee_msat / 1000).saturating_sub(min_balance_sat);
		}
	};
	trim_splice_out_max_if_no_outputs(
		local_nondust_htlc_count,
		channel_constraints.holder_dust_limit_satoshis,
	);
	trim_splice_out_max_if_no_outputs(
		remote_nondust_htlc_count,
		channel_constraints.counterparty_dust_limit_satoshis,
	);

	if channel_value_satoshis < next_splice_out_maximum_sat + MIN_CHANNEL_VALUE_SATOSHIS {
		next_splice_out_maximum_sat =
			channel_value_satoshis.saturating_sub(MIN_CHANNEL_VALUE_SATOSHIS);
	}

	next_splice_out_maximum_sat
}

fn adjust_capacity_for_holder_reserved_fee(
	outbound_capacity_msat: u64, local_nondust_htlc_count: usize, remote_nondust_htlc_count: usize,
	feerate_per_kw: u32, spiked_feerate: u32, channel_constraints: &ChannelConstraints,
	channel_type: &ChannelTypeFeatures,
) -> u64 {
	let read_available_capacity = |nondust_htlc_count, htlc_dust_limit_sat| {
		// Note here we use the htlc count at the current feerate together with the spiked feerate;
		// this makes sure that the holder can afford any fee bump between 1x to 2x from the current
		// feerate.
		let max_commit_tx_fee_sat =
			commit_tx_fee_sat(spiked_feerate, nondust_htlc_count + 2, channel_type);
		let min_commit_tx_fee_sat =
			commit_tx_fee_sat(spiked_feerate, nondust_htlc_count + 1, channel_type);

		// We should mind channel commit tx fee when computing how much of the available capacity
		// can be used in the next htlc. Mirrors the logic in send_htlc.
		//
		// The fee depends on whether the amount we will be sending is above dust or not,
		// and the answer will in turn change the amount itself — making it a circular
		// dependency.
		// This complicates the computation around dust-values, up to the one-htlc-value.

		// We will first subtract the fee as if we were above-dust. Then, if the resulting
		// value ends up being below dust, we have this fee available again. In that case,
		// match the value to right-below-dust.
		let capacity_minus_max_commitment_fee_msat =
			outbound_capacity_msat.saturating_sub(max_commit_tx_fee_sat * 1000);
		if capacity_minus_max_commitment_fee_msat < htlc_dust_limit_sat * 1000 {
			let capacity_minus_min_commitment_fee_msat =
				outbound_capacity_msat.saturating_sub(min_commit_tx_fee_sat * 1000);
			cmp::min(htlc_dust_limit_sat * 1000 - 1, capacity_minus_min_commitment_fee_msat)
		} else {
			capacity_minus_max_commitment_fee_msat
		}
	};

	let (real_htlc_success_tx_fee_sat, real_htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(channel_type, feerate_per_kw);
	let available_capacity_on_local_commitment = read_available_capacity(
		local_nondust_htlc_count,
		channel_constraints.holder_dust_limit_satoshis + real_htlc_timeout_tx_fee_sat,
	);
	let available_capacity_on_remote_commitment = read_available_capacity(
		remote_nondust_htlc_count,
		channel_constraints.counterparty_dust_limit_satoshis + real_htlc_success_tx_fee_sat,
	);
	cmp::min(available_capacity_on_local_commitment, available_capacity_on_remote_commitment)
}

fn adjust_capacity_for_counterparty_reserved_fee(
	outbound_capacity_msat: u64, remote_balance_before_fee_msat: u64,
	local_nondust_htlc_count: usize, remote_nondust_htlc_count: usize, feerate_per_kw: u32,
	channel_constraints: &ChannelConstraints, channel_type: &ChannelTypeFeatures,
) -> u64 {
	let read_available_capacity = |nondust_htlc_count, htlc_dust_limit_sat| {
		let commit_tx_fee_sat =
			commit_tx_fee_sat(feerate_per_kw, nondust_htlc_count + 1, channel_type);
		// If the channel is inbound (i.e. counterparty pays the fee), we need to make sure
		// sending a new HTLC won't reduce their balance below our reserve threshold.
		if remote_balance_before_fee_msat
			< commit_tx_fee_sat * 1000
				+ channel_constraints.holder_selected_channel_reserve_satoshis * 1000
		{
			// If another HTLC's fee would reduce the remote's balance below the reserve limit
			// we've selected for them, we can only send dust HTLCs.
			cmp::min(outbound_capacity_msat, htlc_dust_limit_sat * 1000 - 1)
		} else {
			outbound_capacity_msat
		}
	};
	let (real_htlc_success_tx_fee_sat, real_htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(channel_type, feerate_per_kw);
	let available_capacity_on_local_commitment = read_available_capacity(
		local_nondust_htlc_count,
		channel_constraints.holder_dust_limit_satoshis + real_htlc_timeout_tx_fee_sat,
	);
	let available_capacity_on_remote_commitment = read_available_capacity(
		remote_nondust_htlc_count,
		channel_constraints.counterparty_dust_limit_satoshis + real_htlc_success_tx_fee_sat,
	);
	cmp::min(available_capacity_on_local_commitment, available_capacity_on_remote_commitment)
}

fn adjust_min_max_htlc_for_dust_exposure(
	pending_htlcs: &[HTLCAmountDirection], feerate_per_kw: u32,
	dust_exposure_limiting_feerate: Option<u32>, max_dust_htlc_exposure_msat: u64,
	channel_constraints: &ChannelConstraints, channel_type: &ChannelTypeFeatures,
	mut available_capacity_msat: u64,
) -> (u64, u64, u64) {
	let mut next_outbound_htlc_minimum_msat = channel_constraints.counterparty_htlc_minimum_msat;

	let (local_dust_exposure_msat, _) = get_dust_exposure_stats(
		true,
		pending_htlcs,
		feerate_per_kw,
		dust_exposure_limiting_feerate,
		channel_constraints.holder_dust_limit_satoshis,
		channel_type,
	);
	let (remote_dust_exposure_msat, extra_htlc_remote_dust_exposure_msat) = get_dust_exposure_stats(
		false,
		pending_htlcs,
		feerate_per_kw,
		dust_exposure_limiting_feerate,
		channel_constraints.counterparty_dust_limit_satoshis,
		channel_type,
	);

	// If we get close to our maximum dust exposure, we end up in a situation where we can send
	// between zero and the remaining dust exposure limit remaining OR above the dust limit.
	// Because we cannot express this as a simple min/max, we prefer to tell the user they can
	// send above the dust limit (as the router can always overpay to meet the dust limit).
	let mut remaining_msat_below_dust_exposure_limit = None;
	let mut dust_exposure_dust_limit_msat = 0;

	let dust_buffer_feerate = get_dust_buffer_feerate(feerate_per_kw);
	let (buffer_htlc_success_tx_fee_sat, buffer_htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(channel_type, dust_buffer_feerate);
	let buffer_dust_limit_success_sat =
		buffer_htlc_success_tx_fee_sat + channel_constraints.counterparty_dust_limit_satoshis;
	let buffer_dust_limit_timeout_sat =
		buffer_htlc_timeout_tx_fee_sat + channel_constraints.holder_dust_limit_satoshis;

	if let Some(extra_htlc_remote_dust_exposure) = extra_htlc_remote_dust_exposure_msat {
		if extra_htlc_remote_dust_exposure > max_dust_htlc_exposure_msat {
			// If adding an extra HTLC would put us over the dust limit in total fees, we cannot
			// send any non-dust HTLCs.
			available_capacity_msat =
				cmp::min(available_capacity_msat, buffer_dust_limit_success_sat * 1000);
		}
	}

	if remote_dust_exposure_msat.saturating_add(buffer_dust_limit_success_sat * 1000)
		> max_dust_htlc_exposure_msat.saturating_add(1)
	{
		// Note that we don't use the `counterparty_tx_dust_exposure` (with
		// `htlc_dust_exposure_msat`) here as it only applies to non-dust HTLCs.
		remaining_msat_below_dust_exposure_limit =
			Some(max_dust_htlc_exposure_msat.saturating_sub(remote_dust_exposure_msat));
		dust_exposure_dust_limit_msat =
			cmp::max(dust_exposure_dust_limit_msat, buffer_dust_limit_success_sat * 1000);
	}

	if local_dust_exposure_msat as i64 + buffer_dust_limit_timeout_sat as i64 * 1000 - 1
		> max_dust_htlc_exposure_msat.try_into().unwrap_or(i64::max_value())
	{
		remaining_msat_below_dust_exposure_limit = Some(cmp::min(
			remaining_msat_below_dust_exposure_limit.unwrap_or(u64::max_value()),
			max_dust_htlc_exposure_msat.saturating_sub(local_dust_exposure_msat),
		));
		dust_exposure_dust_limit_msat =
			cmp::max(dust_exposure_dust_limit_msat, buffer_dust_limit_timeout_sat * 1000);
	}

	if let Some(remaining_limit_msat) = remaining_msat_below_dust_exposure_limit {
		if available_capacity_msat < dust_exposure_dust_limit_msat {
			available_capacity_msat = cmp::min(available_capacity_msat, remaining_limit_msat);
		} else {
			next_outbound_htlc_minimum_msat =
				cmp::max(next_outbound_htlc_minimum_msat, dust_exposure_dust_limit_msat);
		}
	}

	let dust_exposure_msat = cmp::max(local_dust_exposure_msat, remote_dust_exposure_msat);

	(next_outbound_htlc_minimum_msat, available_capacity_msat, dust_exposure_msat)
}

fn get_available_balances(
	is_outbound_from_holder: bool, channel_value_satoshis: u64, value_to_holder_msat: u64,
	pending_htlcs: &[HTLCAmountDirection], feerate_per_kw: u32,
	dust_exposure_limiting_feerate: Option<u32>, max_dust_htlc_exposure_msat: u64,
	channel_constraints: ChannelConstraints, channel_type: &ChannelTypeFeatures,
) -> crate::ln::channel::AvailableBalances {
	// When sizing the next HTLC add, we take the remote's view of the set of pending HTLCs in
	// `ChannelContext::get_next_commitment_htlcs`, set this view to `pending_htlcs` here, and use this set of
	// pending HTLCs to calculate stats on our own commitment below.
	//
	// This means we do *not* include `LocalRemoved` HTLCs. `LocalRemoved` and `LocalAnnounced` HTLCs are applied
	// atomically to our own commitment upon the counterparty's next ack.
	//
	// `RemoteRemoved` HTLCs *are* included. While we don't expect these HTLCs to be present in our next
	// commitment, we have not ack'ed these removals yet, so we expect the counterparty to count them when
	// validating our own HTLC add. These HTLCs would also revert to `Committed` upon a disconnection.

	// Note that the feerate is 0 in zero-fee commitment channels, so this statement is a noop
	let spiked_feerate =
		feerate_per_kw.saturating_mul(if !channel_type.supports_anchors_zero_fee_htlc_tx() {
			crate::ln::channel::FEE_SPIKE_BUFFER_FEE_INCREASE_MULTIPLE as u32
		} else {
			1
		});

	let local_nondust_htlc_count = pending_htlcs
		.iter()
		.filter(|htlc| {
			!htlc.is_dust(
				true,
				feerate_per_kw,
				channel_constraints.holder_dust_limit_satoshis,
				channel_type,
			)
		})
		.count();

	let remote_nondust_htlc_count = pending_htlcs
		.iter()
		.filter(|htlc| {
			!htlc.is_dust(
				false,
				feerate_per_kw,
				channel_constraints.counterparty_dust_limit_satoshis,
				channel_type,
			)
		})
		.count();

	let outbound_htlcs_value_msat: u64 =
		pending_htlcs.iter().filter_map(|htlc| htlc.outbound.then_some(htlc.amount_msat)).sum();
	let inbound_htlcs_value_msat: u64 =
		pending_htlcs.iter().filter_map(|htlc| (!htlc.outbound).then_some(htlc.amount_msat)).sum();
	let total_anchors_sat = total_anchors_sat(channel_type);
	let (local_balance_before_fee_msat, remote_balance_before_fee_msat) =
		saturating_sub_from_funder(
			is_outbound_from_holder,
			value_to_holder_msat.saturating_sub(outbound_htlcs_value_msat),
			(channel_value_satoshis * 1000)
				.checked_sub(value_to_holder_msat)
				.unwrap()
				.saturating_sub(inbound_htlcs_value_msat),
			total_anchors_sat.saturating_mul(1000),
		);

	let next_splice_out_maximum_sat = get_next_splice_out_maximum_sat(
		is_outbound_from_holder,
		channel_value_satoshis,
		local_balance_before_fee_msat,
		remote_balance_before_fee_msat,
		local_nondust_htlc_count,
		remote_nondust_htlc_count,
		feerate_per_kw,
		spiked_feerate,
		&channel_constraints,
		channel_type,
	);

	let outbound_capacity_msat = local_balance_before_fee_msat
		.saturating_sub(channel_constraints.counterparty_selected_channel_reserve_satoshis * 1000);

	let available_capacity_msat = if is_outbound_from_holder {
		adjust_capacity_for_holder_reserved_fee(
			outbound_capacity_msat,
			local_nondust_htlc_count,
			remote_nondust_htlc_count,
			feerate_per_kw,
			spiked_feerate,
			&channel_constraints,
			channel_type,
		)
	} else {
		adjust_capacity_for_counterparty_reserved_fee(
			outbound_capacity_msat,
			remote_balance_before_fee_msat,
			local_nondust_htlc_count,
			remote_nondust_htlc_count,
			feerate_per_kw,
			&channel_constraints,
			channel_type,
		)
	};

	let (next_outbound_htlc_minimum_msat, mut available_capacity_msat, dust_exposure_msat) =
		adjust_min_max_htlc_for_dust_exposure(
			pending_htlcs,
			feerate_per_kw,
			dust_exposure_limiting_feerate,
			max_dust_htlc_exposure_msat,
			&channel_constraints,
			channel_type,
			available_capacity_msat,
		);

	available_capacity_msat = cmp::min(
		available_capacity_msat,
		channel_constraints
			.counterparty_max_htlc_value_in_flight_msat
			.saturating_sub(outbound_htlcs_value_msat),
	);

	if pending_htlcs.iter().filter(|htlc| htlc.outbound).count() + 1
		> channel_constraints.counterparty_max_accepted_htlcs as usize
	{
		available_capacity_msat = 0;
	}

	// Now adjust our min and max size HTLC to make sure both the local and the remote commitments still have
	// at least one output at the current feerate.
	let (next_outbound_htlc_minimum_msat, available_capacity_msat) =
		adjust_min_max_htlc_if_max_dust_htlc_produces_no_output(
			is_outbound_from_holder,
			local_balance_before_fee_msat,
			remote_balance_before_fee_msat,
			local_nondust_htlc_count,
			remote_nondust_htlc_count,
			feerate_per_kw,
			&channel_constraints,
			channel_type,
			next_outbound_htlc_minimum_msat,
			available_capacity_msat,
		);

	crate::ln::channel::AvailableBalances {
		inbound_capacity_msat: remote_balance_before_fee_msat
			.saturating_sub(channel_constraints.holder_selected_channel_reserve_satoshis * 1000),
		outbound_capacity_msat,
		next_outbound_htlc_limit_msat: available_capacity_msat,
		next_outbound_htlc_minimum_msat,
		dust_exposure_msat,
		next_splice_out_maximum_sat,
	}
}

fn adjust_min_max_htlc_if_max_dust_htlc_produces_no_output(
	is_outbound_from_holder: bool, local_balance_before_fee_msat: u64,
	remote_balance_before_fee_msat: u64, local_nondust_htlc_count: usize,
	remote_nondust_htlc_count: usize, feerate_per_kw: u32,
	channel_constraints: &ChannelConstraints, channel_type: &ChannelTypeFeatures,
	next_outbound_htlc_minimum_msat: u64, available_capacity_msat: u64,
) -> (u64, u64) {
	let (next_outbound_htlc_minimum_msat, available_capacity_msat) =
		adjust_boundaries_if_max_dust_htlc_produces_no_output(
			true,
			is_outbound_from_holder,
			local_balance_before_fee_msat,
			remote_balance_before_fee_msat,
			feerate_per_kw,
			local_nondust_htlc_count,
			channel_constraints.holder_dust_limit_satoshis,
			channel_type,
			next_outbound_htlc_minimum_msat,
			available_capacity_msat,
		);

	let (next_outbound_htlc_minimum_msat, available_capacity_msat) =
		adjust_boundaries_if_max_dust_htlc_produces_no_output(
			false,
			is_outbound_from_holder,
			local_balance_before_fee_msat,
			remote_balance_before_fee_msat,
			feerate_per_kw,
			remote_nondust_htlc_count,
			channel_constraints.counterparty_dust_limit_satoshis,
			channel_type,
			next_outbound_htlc_minimum_msat,
			available_capacity_msat,
		);
	(next_outbound_htlc_minimum_msat, available_capacity_msat)
}

fn adjust_boundaries_if_max_dust_htlc_produces_no_output(
	local: bool, is_outbound_from_holder: bool, holder_balance_before_fee_msat: u64,
	counterparty_balance_before_fee_msat: u64, feerate_per_kw: u32, nondust_htlc_count: usize,
	dust_limit_satoshis: u64, channel_type: &ChannelTypeFeatures,
	next_outbound_htlc_minimum_msat: u64, available_capacity_msat: u64,
) -> (u64, u64) {
	// First, determine the biggest dust HTLC we could send
	let (htlc_success_tx_fee_sat, htlc_timeout_tx_fee_sat) =
		second_stage_tx_fees_sat(channel_type, feerate_per_kw);
	let min_nondust_htlc_sat =
		dust_limit_satoshis + if local { htlc_timeout_tx_fee_sat } else { htlc_success_tx_fee_sat };
	let max_dust_htlc_msat = (min_nondust_htlc_sat.saturating_mul(1000)).saturating_sub(1);

	// If this dust HTLC produces no outputs, then we have to say something! It is now possible to produce a
	// commitment with no outputs.
	if !has_output(
		is_outbound_from_holder,
		holder_balance_before_fee_msat.saturating_sub(max_dust_htlc_msat),
		counterparty_balance_before_fee_msat,
		feerate_per_kw,
		nondust_htlc_count,
		dust_limit_satoshis,
		channel_type,
	) {
		// If we are allowed to send non-dust HTLCs, set the min HTLC to the smallest non-dust HTLC...
		if available_capacity_msat >= min_nondust_htlc_sat.saturating_mul(1000) {
			(
				cmp::max(
					min_nondust_htlc_sat.saturating_mul(1000),
					next_outbound_htlc_minimum_msat,
				),
				available_capacity_msat,
			)
		// Otherwise, set the max HTLC to the biggest that still leaves our main balance output untrimmed.
		// Note that this will be a dust HTLC.
		} else {
			// Remember we've got no non-dust HTLCs on the commitment here
			let current_tx_fee_sat = commit_tx_fee_sat(feerate_per_kw, 0, channel_type);
			let spike_buffer_tx_fee_sat = commit_tx_fee_sat(feerate_per_kw, 1, channel_type);
			// In case we are the funder, we must cover the greater of
			// 1) The dust_limit_satoshis plus the fee of the existing commitment at the current feerate.
			// 2) The fee of the commitment with an additional non-dust HTLC, aka the fee spike buffer HTLC.
			//    In this case we don't mind the holder balance output dropping below the dust limit, as
			//    this additional non-dust HTLC will create the single remaining output on the commitment.
			let min_balance_msat = if is_outbound_from_holder {
				cmp::max(dust_limit_satoshis + current_tx_fee_sat, spike_buffer_tx_fee_sat) * 1000
			// In case we are the fundee, we can send dust HTLCs as long as our own balance output
			// remains above the dust limit.
			} else {
				dust_limit_satoshis * 1000
			};
			(
				next_outbound_htlc_minimum_msat,
				// We make no assumptions about the size of `available_capacity_msat` passed to this
				// function, we only care that the new `available_capacity_msat` is under
				// `holder_balance_before_fee_msat - min_balance_msat`
				cmp::min(
					holder_balance_before_fee_msat.saturating_sub(min_balance_msat),
					available_capacity_msat,
				),
			)
		}
	// Otherwise, it is impossible to produce no outputs with this upcoming HTLC add, so we stay quiet
	} else {
		(next_outbound_htlc_minimum_msat, available_capacity_msat)
	}
}

pub(crate) trait TxBuilder {
	fn get_channel_stats(
		&self, local: bool, is_outbound_from_holder: bool, channel_value_satoshis: u64,
		value_to_holder_msat: u64, pending_htlcs: &[HTLCAmountDirection],
		addl_nondust_htlc_count: usize, feerate_per_kw: u32, assume_fee_spike: bool,
		dust_exposure_limiting_feerate: Option<u32>, max_dust_htlc_exposure_msat: u64,
		channel_constraints: ChannelConstraints, channel_type: &ChannelTypeFeatures,
	) -> Result<ChannelStats, ()>;
	fn build_commitment_transaction<L: Logger>(
		&self, local: bool, commitment_number: u64, per_commitment_point: &PublicKey,
		channel_parameters: &ChannelTransactionParameters, secp_ctx: &Secp256k1<secp256k1::All>,
		value_to_self_msat: u64, htlcs_in_tx: Vec<HTLCOutputInCommitment>, feerate_per_kw: u32,
		broadcaster_dust_limit_satoshis: u64, logger: &L,
	) -> (CommitmentTransaction, CommitmentStats);
}

pub(crate) struct SpecTxBuilder {}

impl TxBuilder for SpecTxBuilder {
	fn get_channel_stats(
		&self, local: bool, is_outbound_from_holder: bool, channel_value_satoshis: u64,
		value_to_holder_msat: u64, pending_htlcs: &[HTLCAmountDirection],
		addl_nondust_htlc_count: usize, feerate_per_kw: u32, assume_fee_spike: bool,
		dust_exposure_limiting_feerate: Option<u32>, max_dust_htlc_exposure_msat: u64,
		channel_constraints: ChannelConstraints, channel_type: &ChannelTypeFeatures,
	) -> Result<ChannelStats, ()> {
		let commitment_stats = if local {
			get_next_commitment_stats(
				true,
				is_outbound_from_holder,
				channel_value_satoshis,
				value_to_holder_msat,
				pending_htlcs,
				addl_nondust_htlc_count,
				feerate_per_kw,
				assume_fee_spike,
				dust_exposure_limiting_feerate,
				channel_constraints.holder_dust_limit_satoshis,
				channel_type,
			)?
		} else {
			get_next_commitment_stats(
				false,
				is_outbound_from_holder,
				channel_value_satoshis,
				value_to_holder_msat,
				pending_htlcs,
				addl_nondust_htlc_count,
				feerate_per_kw,
				assume_fee_spike,
				dust_exposure_limiting_feerate,
				channel_constraints.counterparty_dust_limit_satoshis,
				channel_type,
			)?
		};

		let available_balances = get_available_balances(
			is_outbound_from_holder,
			channel_value_satoshis,
			value_to_holder_msat,
			pending_htlcs,
			feerate_per_kw,
			dust_exposure_limiting_feerate,
			max_dust_htlc_exposure_msat,
			channel_constraints,
			channel_type,
		);

		Ok(ChannelStats { commitment_stats, available_balances })
	}
	fn build_commitment_transaction<L: Logger>(
		&self, local: bool, commitment_number: u64, per_commitment_point: &PublicKey,
		channel_parameters: &ChannelTransactionParameters, secp_ctx: &Secp256k1<secp256k1::All>,
		value_to_self_msat: u64, mut htlcs_in_tx: Vec<HTLCOutputInCommitment>, feerate_per_kw: u32,
		broadcaster_dust_limit_satoshis: u64, logger: &L,
	) -> (CommitmentTransaction, CommitmentStats) {
		let mut local_htlc_total_msat = 0;
		let mut remote_htlc_total_msat = 0;
		let channel_type = &channel_parameters.channel_type_features;

		let is_dust = |offered: bool, amount_msat: u64| -> bool {
			let htlc_tx_fee_sat = if channel_type.supports_anchors_zero_fee_htlc_tx() {
				0
			} else {
				let htlc_tx_weight = if offered {
					htlc_timeout_tx_weight(channel_type)
				} else {
					htlc_success_tx_weight(channel_type)
				};
				// As required by the spec, round down
				feerate_per_kw as u64 * htlc_tx_weight / 1000
			};
			amount_msat / 1000 < broadcaster_dust_limit_satoshis + htlc_tx_fee_sat
		};

		// Trim dust htlcs
		htlcs_in_tx.retain(|htlc| {
			if htlc.offered == local {
				// This is an outbound htlc
				local_htlc_total_msat += htlc.amount_msat;
			} else {
				remote_htlc_total_msat += htlc.amount_msat;
			}
			if is_dust(htlc.offered, htlc.amount_msat) {
				log_trace!(
					logger,
					"   ...trimming {} HTLC with value {}sat, hash {}, due to dust limit {}",
					if htlc.offered == local { "outbound" } else { "inbound" },
					htlc.amount_msat / 1000,
					htlc.payment_hash,
					broadcaster_dust_limit_satoshis
				);
				false
			} else {
				true
			}
		});

		// # Panics
		//
		// The value going to each party MUST be 0 or positive, even if all HTLCs pending in the
		// commitment clear by failure.

		let commit_tx_fee_sat = commit_tx_fee_sat(
			feerate_per_kw,
			htlcs_in_tx.len(),
			&channel_parameters.channel_type_features,
		);
		let value_to_self_after_htlcs_msat =
			value_to_self_msat.checked_sub(local_htlc_total_msat).unwrap();
		let value_to_remote_after_htlcs_msat = (channel_parameters.channel_value_satoshis * 1000)
			.checked_sub(value_to_self_msat)
			.unwrap()
			.checked_sub(remote_htlc_total_msat)
			.unwrap();

		// We MUST use saturating subs here, as the funder's balance is not guaranteed to be greater
		// than or equal to `total_anchors_sat`.
		//
		// This is because when the remote party sends an `update_fee` message, we build the new
		// commitment transaction *before* checking whether the remote party's balance is enough to
		// cover the total anchor sum.

		let total_anchors_sat = total_anchors_sat(&channel_parameters.channel_type_features);
		let (local_balance_before_fee_msat, remote_balance_before_fee_msat) =
			saturating_sub_from_funder(
				channel_parameters.is_outbound_from_holder,
				value_to_self_after_htlcs_msat,
				value_to_remote_after_htlcs_msat,
				total_anchors_sat.saturating_mul(1000),
			);

		// We MUST use saturating subs here, as the funder's balance is not guaranteed to be greater
		// than or equal to `commit_tx_fee_sat`.
		//
		// This is because when the remote party sends an `update_fee` message, we build the new
		// commitment transaction *before* checking whether the remote party's balance is enough to
		// cover the total fee.

		let (value_to_self, value_to_remote) = saturating_sub_from_funder(
			channel_parameters.is_outbound_from_holder,
			local_balance_before_fee_msat / 1000,
			remote_balance_before_fee_msat / 1000,
			commit_tx_fee_sat,
		);

		let mut to_broadcaster_value_sat = if local { value_to_self } else { value_to_remote };
		let mut to_countersignatory_value_sat = if local { value_to_remote } else { value_to_self };

		if to_broadcaster_value_sat >= broadcaster_dust_limit_satoshis {
			log_trace!(
				logger,
				"   ...including {} output with value {}",
				if local { "to_local" } else { "to_remote" },
				to_broadcaster_value_sat
			);
		} else {
			to_broadcaster_value_sat = 0;
		}

		if to_countersignatory_value_sat >= broadcaster_dust_limit_satoshis {
			log_trace!(
				logger,
				"   ...including {} output with value {}",
				if local { "to_remote" } else { "to_local" },
				to_countersignatory_value_sat
			);
		} else {
			to_countersignatory_value_sat = 0;
		}

		let directed_parameters = if local {
			channel_parameters.as_holder_broadcastable()
		} else {
			channel_parameters.as_counterparty_broadcastable()
		};
		let tx = CommitmentTransaction::new(
			commitment_number,
			per_commitment_point,
			to_broadcaster_value_sat,
			to_countersignatory_value_sat,
			feerate_per_kw,
			htlcs_in_tx,
			&directed_parameters,
			secp_ctx,
		);

		(
			tx,
			CommitmentStats {
				commit_tx_fee_sat,
				local_balance_before_fee_msat,
				remote_balance_before_fee_msat,
			},
		)
	}
}