-
Notifications
You must be signed in to change notification settings - Fork 400
/
Copy pathpackage.rs
1755 lines (1603 loc) · 77.2 KB
/
package.rs
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.
//! Various utilities to assemble claimable outpoints in package of one or more transactions. Those
//! packages are attached metadata, guiding their aggregable or fee-bumping re-schedule. This file
//! also includes witness weight computation and fee computation methods.
use bitcoin::{Sequence, Witness};
use bitcoin::amount::Amount;
use bitcoin::constants::WITNESS_SCALE_FACTOR;
use bitcoin::locktime::absolute::LockTime;
use bitcoin::transaction::{TxOut,TxIn, Transaction};
use bitcoin::transaction::OutPoint as BitcoinOutPoint;
use bitcoin::script::{Script, ScriptBuf};
use bitcoin::hash_types::Txid;
use bitcoin::secp256k1::{SecretKey,PublicKey};
use bitcoin::sighash::EcdsaSighashType;
use bitcoin::transaction::Version;
use crate::types::payment::PaymentPreimage;
use crate::ln::chan_utils::{self, TxCreationKeys, HTLCOutputInCommitment};
use crate::types::features::ChannelTypeFeatures;
use crate::ln::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint};
use crate::ln::channelmanager::MIN_CLTV_EXPIRY_DELTA;
use crate::ln::msgs::DecodeError;
use crate::chain::channelmonitor::COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, INCREMENTAL_RELAY_FEE_SAT_PER_1000_WEIGHT, compute_feerate_sat_per_1000_weight, FEERATE_FLOOR_SATS_PER_KW};
use crate::chain::transaction::MaybeSignedTransaction;
use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::chain::onchaintx::{FeerateStrategy, ExternalHTLCClaim, OnchainTxHandler};
use crate::util::logger::Logger;
use crate::util::ser::{Readable, Writer, Writeable, RequiredWrapper};
use crate::io;
use core::cmp;
use core::ops::Deref;
#[allow(unused_imports)]
use crate::prelude::*;
use super::chaininterface::LowerBoundedFeeEstimator;
const MAX_ALLOC_SIZE: usize = 64*1024;
pub(crate) fn weight_revoked_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
const WEIGHT_REVOKED_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 133;
const WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_OFFERED_HTLC_ANCHORS } else { WEIGHT_REVOKED_OFFERED_HTLC }
}
pub(crate) fn weight_revoked_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
// number_of_witness_elements + sig_length + revocation_sig + pubkey_length + revocationpubkey + witness_script_length + witness_script
const WEIGHT_REVOKED_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 33 + 1 + 139;
const WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_REVOKED_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_REVOKED_RECEIVED_HTLC_ANCHORS } else { WEIGHT_REVOKED_RECEIVED_HTLC }
}
pub(crate) fn weight_offered_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
// number_of_witness_elements + sig_length + counterpartyhtlc_sig + preimage_length + preimage + witness_script_length + witness_script
const WEIGHT_OFFERED_HTLC: u64 = 1 + 1 + 73 + 1 + 32 + 1 + 133;
const WEIGHT_OFFERED_HTLC_ANCHORS: u64 = WEIGHT_OFFERED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_OFFERED_HTLC_ANCHORS } else { WEIGHT_OFFERED_HTLC }
}
pub(crate) fn weight_received_htlc(channel_type_features: &ChannelTypeFeatures) -> u64 {
// number_of_witness_elements + sig_length + counterpartyhtlc_sig + empty_vec_length + empty_vec + witness_script_length + witness_script
const WEIGHT_RECEIVED_HTLC: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 139;
const WEIGHT_RECEIVED_HTLC_ANCHORS: u64 = WEIGHT_RECEIVED_HTLC + 3; // + OP_1 + OP_CSV + OP_DROP
if channel_type_features.supports_anchors_zero_fee_htlc_tx() { WEIGHT_RECEIVED_HTLC_ANCHORS } else { WEIGHT_RECEIVED_HTLC }
}
/// Verifies deserializable channel type features
pub(crate) fn verify_channel_type_features(channel_type_features: &Option<ChannelTypeFeatures>, additional_permitted_features: Option<&ChannelTypeFeatures>) -> Result<(), DecodeError> {
if let Some(features) = channel_type_features.as_ref() {
if features.requires_unknown_bits() {
return Err(DecodeError::UnknownRequiredFeature);
}
let mut supported_feature_set = ChannelTypeFeatures::anchors_zero_htlc_fee_and_dependencies();
supported_feature_set.set_scid_privacy_required();
supported_feature_set.set_zero_conf_required();
// allow the passing of an additional necessary permitted flag
if let Some(additional_permitted_features) = additional_permitted_features {
supported_feature_set |= additional_permitted_features;
}
if features.requires_unknown_bits_from(&supported_feature_set) {
return Err(DecodeError::UnknownRequiredFeature);
}
}
Ok(())
}
// number_of_witness_elements + sig_length + revocation_sig + true_length + op_true + witness_script_length + witness_script
pub(crate) const WEIGHT_REVOKED_OUTPUT: u64 = 1 + 1 + 73 + 1 + 1 + 1 + 77;
#[cfg(not(test))]
/// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;
#[cfg(test)]
/// Height delay at which transactions are fee-bumped/rebroadcasted with a low priority.
pub(crate) const LOW_FREQUENCY_BUMP_INTERVAL: u32 = 15;
/// Height delay at which transactions are fee-bumped/rebroadcasted with a middle priority.
const MIDDLE_FREQUENCY_BUMP_INTERVAL: u32 = 3;
/// Height delay at which transactions are fee-bumped/rebroadcasted with a high priority.
const HIGH_FREQUENCY_BUMP_INTERVAL: u32 = 1;
/// A struct to describe a revoked output and corresponding information to generate a solving
/// witness spending a commitment `to_local` output or a second-stage HTLC transaction output.
///
/// CSV and pubkeys are used as part of a witnessScript redeeming a balance output, amount is used
/// as part of the signature hash and revocation secret to generate a satisfying witness.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct RevokedOutput {
per_commitment_point: PublicKey,
counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
counterparty_htlc_base_key: HtlcBasepoint,
per_commitment_key: SecretKey,
weight: u64,
amount: Amount,
on_counterparty_tx_csv: u16,
is_counterparty_balance_on_anchors: Option<()>,
}
impl RevokedOutput {
pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, counterparty_htlc_base_key: HtlcBasepoint, per_commitment_key: SecretKey, amount: Amount, on_counterparty_tx_csv: u16, is_counterparty_balance_on_anchors: bool) -> Self {
RevokedOutput {
per_commitment_point,
counterparty_delayed_payment_base_key,
counterparty_htlc_base_key,
per_commitment_key,
weight: WEIGHT_REVOKED_OUTPUT,
amount,
on_counterparty_tx_csv,
is_counterparty_balance_on_anchors: if is_counterparty_balance_on_anchors { Some(()) } else { None }
}
}
}
impl_writeable_tlv_based!(RevokedOutput, {
(0, per_commitment_point, required),
(2, counterparty_delayed_payment_base_key, required),
(4, counterparty_htlc_base_key, required),
(6, per_commitment_key, required),
(8, weight, required),
(10, amount, required),
(12, on_counterparty_tx_csv, required),
(14, is_counterparty_balance_on_anchors, option)
});
/// A struct to describe a revoked offered output and corresponding information to generate a
/// solving witness.
///
/// HTLCOuputInCommitment (hash timelock, direction) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// CSV is used as part of a witnessScript redeeming a balance output, amount is used as part
/// of the signature hash and revocation secret to generate a satisfying witness.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct RevokedHTLCOutput {
per_commitment_point: PublicKey,
counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
counterparty_htlc_base_key: HtlcBasepoint,
per_commitment_key: SecretKey,
weight: u64,
amount: u64,
htlc: HTLCOutputInCommitment,
}
impl RevokedHTLCOutput {
pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, counterparty_htlc_base_key: HtlcBasepoint, per_commitment_key: SecretKey, amount: u64, htlc: HTLCOutputInCommitment, channel_type_features: &ChannelTypeFeatures) -> Self {
let weight = if htlc.offered { weight_revoked_offered_htlc(channel_type_features) } else { weight_revoked_received_htlc(channel_type_features) };
RevokedHTLCOutput {
per_commitment_point,
counterparty_delayed_payment_base_key,
counterparty_htlc_base_key,
per_commitment_key,
weight,
amount,
htlc
}
}
}
impl_writeable_tlv_based!(RevokedHTLCOutput, {
(0, per_commitment_point, required),
(2, counterparty_delayed_payment_base_key, required),
(4, counterparty_htlc_base_key, required),
(6, per_commitment_key, required),
(8, weight, required),
(10, amount, required),
(12, htlc, required),
});
/// A struct to describe a HTLC output on a counterparty commitment transaction.
///
/// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// The preimage is used as part of the witness.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct CounterpartyOfferedHTLCOutput {
per_commitment_point: PublicKey,
counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
counterparty_htlc_base_key: HtlcBasepoint,
preimage: PaymentPreimage,
htlc: HTLCOutputInCommitment,
channel_type_features: ChannelTypeFeatures,
}
impl CounterpartyOfferedHTLCOutput {
pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, counterparty_htlc_base_key: HtlcBasepoint, preimage: PaymentPreimage, htlc: HTLCOutputInCommitment, channel_type_features: ChannelTypeFeatures) -> Self {
CounterpartyOfferedHTLCOutput {
per_commitment_point,
counterparty_delayed_payment_base_key,
counterparty_htlc_base_key,
preimage,
htlc,
channel_type_features,
}
}
}
impl Writeable for CounterpartyOfferedHTLCOutput {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
write_tlv_fields!(writer, {
(0, self.per_commitment_point, required),
(2, self.counterparty_delayed_payment_base_key, required),
(4, self.counterparty_htlc_base_key, required),
(6, self.preimage, required),
(8, self.htlc, required),
(10, legacy_deserialization_prevention_marker, option),
(11, self.channel_type_features, required),
});
Ok(())
}
}
impl Readable for CounterpartyOfferedHTLCOutput {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let mut per_commitment_point = RequiredWrapper(None);
let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
let mut counterparty_htlc_base_key = RequiredWrapper(None);
let mut preimage = RequiredWrapper(None);
let mut htlc = RequiredWrapper(None);
let mut _legacy_deserialization_prevention_marker: Option<()> = None;
let mut channel_type_features = None;
read_tlv_fields!(reader, {
(0, per_commitment_point, required),
(2, counterparty_delayed_payment_base_key, required),
(4, counterparty_htlc_base_key, required),
(6, preimage, required),
(8, htlc, required),
(10, _legacy_deserialization_prevention_marker, option),
(11, channel_type_features, option),
});
verify_channel_type_features(&channel_type_features, None)?;
Ok(Self {
per_commitment_point: per_commitment_point.0.unwrap(),
counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
preimage: preimage.0.unwrap(),
htlc: htlc.0.unwrap(),
channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
})
}
}
/// A struct to describe a HTLC output on a counterparty commitment transaction.
///
/// HTLCOutputInCommitment (hash, timelock, directon) and pubkeys are used to generate a suitable
/// witnessScript.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct CounterpartyReceivedHTLCOutput {
per_commitment_point: PublicKey,
counterparty_delayed_payment_base_key: DelayedPaymentBasepoint,
counterparty_htlc_base_key: HtlcBasepoint,
htlc: HTLCOutputInCommitment,
channel_type_features: ChannelTypeFeatures,
}
impl CounterpartyReceivedHTLCOutput {
pub(crate) fn build(per_commitment_point: PublicKey, counterparty_delayed_payment_base_key: DelayedPaymentBasepoint, counterparty_htlc_base_key: HtlcBasepoint, htlc: HTLCOutputInCommitment, channel_type_features: ChannelTypeFeatures) -> Self {
CounterpartyReceivedHTLCOutput {
per_commitment_point,
counterparty_delayed_payment_base_key,
counterparty_htlc_base_key,
htlc,
channel_type_features
}
}
}
impl Writeable for CounterpartyReceivedHTLCOutput {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
write_tlv_fields!(writer, {
(0, self.per_commitment_point, required),
(2, self.counterparty_delayed_payment_base_key, required),
(4, self.counterparty_htlc_base_key, required),
(6, self.htlc, required),
(8, legacy_deserialization_prevention_marker, option),
(9, self.channel_type_features, required),
});
Ok(())
}
}
impl Readable for CounterpartyReceivedHTLCOutput {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let mut per_commitment_point = RequiredWrapper(None);
let mut counterparty_delayed_payment_base_key = RequiredWrapper(None);
let mut counterparty_htlc_base_key = RequiredWrapper(None);
let mut htlc = RequiredWrapper(None);
let mut _legacy_deserialization_prevention_marker: Option<()> = None;
let mut channel_type_features = None;
read_tlv_fields!(reader, {
(0, per_commitment_point, required),
(2, counterparty_delayed_payment_base_key, required),
(4, counterparty_htlc_base_key, required),
(6, htlc, required),
(8, _legacy_deserialization_prevention_marker, option),
(9, channel_type_features, option),
});
verify_channel_type_features(&channel_type_features, None)?;
Ok(Self {
per_commitment_point: per_commitment_point.0.unwrap(),
counterparty_delayed_payment_base_key: counterparty_delayed_payment_base_key.0.unwrap(),
counterparty_htlc_base_key: counterparty_htlc_base_key.0.unwrap(),
htlc: htlc.0.unwrap(),
channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
})
}
}
/// A struct to describe a HTLC output on holder commitment transaction.
///
/// Either offered or received, the amount is always used as part of the bip143 sighash.
/// Preimage is only included as part of the witness in former case.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct HolderHTLCOutput {
preimage: Option<PaymentPreimage>,
amount_msat: u64,
/// Defaults to 0 for HTLC-Success transactions, which have no expiry
cltv_expiry: u32,
channel_type_features: ChannelTypeFeatures,
}
impl HolderHTLCOutput {
pub(crate) fn build_offered(amount_msat: u64, cltv_expiry: u32, channel_type_features: ChannelTypeFeatures) -> Self {
HolderHTLCOutput {
preimage: None,
amount_msat,
cltv_expiry,
channel_type_features,
}
}
pub(crate) fn build_accepted(preimage: PaymentPreimage, amount_msat: u64, channel_type_features: ChannelTypeFeatures) -> Self {
HolderHTLCOutput {
preimage: Some(preimage),
amount_msat,
cltv_expiry: 0,
channel_type_features,
}
}
}
impl Writeable for HolderHTLCOutput {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
write_tlv_fields!(writer, {
(0, self.amount_msat, required),
(2, self.cltv_expiry, required),
(4, self.preimage, option),
(6, legacy_deserialization_prevention_marker, option),
(7, self.channel_type_features, required),
});
Ok(())
}
}
impl Readable for HolderHTLCOutput {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let mut amount_msat = RequiredWrapper(None);
let mut cltv_expiry = RequiredWrapper(None);
let mut preimage = None;
let mut _legacy_deserialization_prevention_marker: Option<()> = None;
let mut channel_type_features = None;
read_tlv_fields!(reader, {
(0, amount_msat, required),
(2, cltv_expiry, required),
(4, preimage, option),
(6, _legacy_deserialization_prevention_marker, option),
(7, channel_type_features, option),
});
verify_channel_type_features(&channel_type_features, None)?;
Ok(Self {
amount_msat: amount_msat.0.unwrap(),
cltv_expiry: cltv_expiry.0.unwrap(),
preimage,
channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key())
})
}
}
/// A struct to describe the channel output on the funding transaction.
///
/// witnessScript is used as part of the witness redeeming the funding utxo.
///
/// Note that on upgrades, some features of existing outputs may be missed.
#[derive(Clone, PartialEq, Eq)]
pub(crate) struct HolderFundingOutput {
funding_redeemscript: ScriptBuf,
pub(crate) funding_amount: Option<u64>,
channel_type_features: ChannelTypeFeatures,
}
impl HolderFundingOutput {
pub(crate) fn build(funding_redeemscript: ScriptBuf, funding_amount: u64, channel_type_features: ChannelTypeFeatures) -> Self {
HolderFundingOutput {
funding_redeemscript,
funding_amount: Some(funding_amount),
channel_type_features,
}
}
}
impl Writeable for HolderFundingOutput {
fn write<W: Writer>(&self, writer: &mut W) -> Result<(), io::Error> {
let legacy_deserialization_prevention_marker = chan_utils::legacy_deserialization_prevention_marker_for_channel_type_features(&self.channel_type_features);
write_tlv_fields!(writer, {
(0, self.funding_redeemscript, required),
(1, self.channel_type_features, required),
(2, legacy_deserialization_prevention_marker, option),
(3, self.funding_amount, option),
});
Ok(())
}
}
impl Readable for HolderFundingOutput {
fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
let mut funding_redeemscript = RequiredWrapper(None);
let mut _legacy_deserialization_prevention_marker: Option<()> = None;
let mut channel_type_features = None;
let mut funding_amount = None;
read_tlv_fields!(reader, {
(0, funding_redeemscript, required),
(1, channel_type_features, option),
(2, _legacy_deserialization_prevention_marker, option),
(3, funding_amount, option),
});
verify_channel_type_features(&channel_type_features, None)?;
Ok(Self {
funding_redeemscript: funding_redeemscript.0.unwrap(),
channel_type_features: channel_type_features.unwrap_or(ChannelTypeFeatures::only_static_remote_key()),
funding_amount
})
}
}
/// A wrapper encapsulating all in-protocol differing outputs types.
///
/// The generic API offers access to an outputs common attributes or allow transformation such as
/// finalizing an input claiming the output.
#[derive(Clone, PartialEq, Eq)]
pub(crate) enum PackageSolvingData {
RevokedOutput(RevokedOutput),
RevokedHTLCOutput(RevokedHTLCOutput),
CounterpartyOfferedHTLCOutput(CounterpartyOfferedHTLCOutput),
CounterpartyReceivedHTLCOutput(CounterpartyReceivedHTLCOutput),
HolderHTLCOutput(HolderHTLCOutput),
HolderFundingOutput(HolderFundingOutput),
}
impl PackageSolvingData {
fn amount(&self) -> u64 {
let amt = match self {
PackageSolvingData::RevokedOutput(ref outp) => outp.amount.to_sat(),
PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.amount,
PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => outp.htlc.amount_msat / 1000,
PackageSolvingData::HolderHTLCOutput(ref outp) => {
debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
outp.amount_msat / 1000
},
PackageSolvingData::HolderFundingOutput(ref outp) => {
debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
outp.funding_amount.unwrap()
}
};
amt
}
fn weight(&self) -> usize {
match self {
PackageSolvingData::RevokedOutput(ref outp) => outp.weight as usize,
PackageSolvingData::RevokedHTLCOutput(ref outp) => outp.weight as usize,
PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => weight_offered_htlc(&outp.channel_type_features) as usize,
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => weight_received_htlc(&outp.channel_type_features) as usize,
PackageSolvingData::HolderHTLCOutput(ref outp) => {
debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
if outp.preimage.is_none() {
weight_offered_htlc(&outp.channel_type_features) as usize
} else {
weight_received_htlc(&outp.channel_type_features) as usize
}
},
// Since HolderFundingOutput maps to an untractable package that is already signed, its
// weight can be determined from the transaction itself.
PackageSolvingData::HolderFundingOutput(..) => unreachable!(),
}
}
/// Checks if this and `other` are spending types of inputs which could have descended from the
/// same commitment transaction(s) and thus could both be spent without requiring a
/// double-spend.
fn is_possibly_from_same_tx_tree(&self, other: &PackageSolvingData) -> bool {
match self {
PackageSolvingData::RevokedOutput(_)|PackageSolvingData::RevokedHTLCOutput(_) => {
match other {
PackageSolvingData::RevokedOutput(_)|
PackageSolvingData::RevokedHTLCOutput(_) => true,
_ => false,
}
},
PackageSolvingData::CounterpartyOfferedHTLCOutput(_)|
PackageSolvingData::CounterpartyReceivedHTLCOutput(_) => {
match other {
PackageSolvingData::CounterpartyOfferedHTLCOutput(_)|
PackageSolvingData::CounterpartyReceivedHTLCOutput(_) => true,
_ => false,
}
},
PackageSolvingData::HolderHTLCOutput(_)|
PackageSolvingData::HolderFundingOutput(_) => {
match other {
PackageSolvingData::HolderHTLCOutput(_)|
PackageSolvingData::HolderFundingOutput(_) => true,
_ => false,
}
},
}
}
fn as_tx_input(&self, previous_output: BitcoinOutPoint) -> TxIn {
let sequence = match self {
PackageSolvingData::RevokedOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
PackageSolvingData::RevokedHTLCOutput(_) => Sequence::ENABLE_RBF_NO_LOCKTIME,
PackageSolvingData::CounterpartyOfferedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
Sequence::from_consensus(1)
} else {
Sequence::ENABLE_RBF_NO_LOCKTIME
},
PackageSolvingData::CounterpartyReceivedHTLCOutput(outp) => if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() {
Sequence::from_consensus(1)
} else {
Sequence::ENABLE_RBF_NO_LOCKTIME
},
_ => {
debug_assert!(false, "This should not be reachable by 'untractable' or 'malleable with external funding' packages");
Sequence::ENABLE_RBF_NO_LOCKTIME
},
};
TxIn {
previous_output,
script_sig: ScriptBuf::new(),
sequence,
witness: Witness::new(),
}
}
fn finalize_input<Signer: EcdsaChannelSigner>(&self, bumped_tx: &mut Transaction, i: usize, onchain_handler: &mut OnchainTxHandler<Signer>) -> bool {
match self {
PackageSolvingData::RevokedOutput(ref outp) => {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_revokeable_redeemscript(&chan_keys.revocation_key, outp.on_counterparty_tx_csv, &chan_keys.broadcaster_delayed_payment_key);
//TODO: should we panic on signer failure ?
if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_output(&bumped_tx, i, outp.amount.to_sat(), &outp.per_commitment_key, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
bumped_tx.input[i].witness.push(ser_sig);
bumped_tx.input[i].witness.push(vec!(1));
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
} else { return false; }
},
PackageSolvingData::RevokedHTLCOutput(ref outp) => {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
//TODO: should we panic on signer failure ?
if let Ok(sig) = onchain_handler.signer.sign_justice_revoked_htlc(&bumped_tx, i, outp.amount, &outp.per_commitment_key, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
bumped_tx.input[i].witness.push(ser_sig);
bumped_tx.input[i].witness.push(chan_keys.revocation_key.to_public_key().serialize().to_vec());
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
} else { return false; }
},
PackageSolvingData::CounterpartyOfferedHTLCOutput(ref outp) => {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
bumped_tx.input[i].witness.push(ser_sig);
bumped_tx.input[i].witness.push(outp.preimage.0.to_vec());
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
}
},
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => {
let chan_keys = TxCreationKeys::derive_new(&onchain_handler.secp_ctx, &outp.per_commitment_point, &outp.counterparty_delayed_payment_base_key, &outp.counterparty_htlc_base_key, &onchain_handler.signer.pubkeys().revocation_basepoint, &onchain_handler.signer.pubkeys().htlc_basepoint);
let witness_script = chan_utils::get_htlc_redeemscript_with_explicit_keys(&outp.htlc, &onchain_handler.channel_type_features(), &chan_keys.broadcaster_htlc_key, &chan_keys.countersignatory_htlc_key, &chan_keys.revocation_key);
if let Ok(sig) = onchain_handler.signer.sign_counterparty_htlc_transaction(&bumped_tx, i, &outp.htlc.amount_msat / 1000, &outp.per_commitment_point, &outp.htlc, &onchain_handler.secp_ctx) {
let mut ser_sig = sig.serialize_der().to_vec();
ser_sig.push(EcdsaSighashType::All as u8);
bumped_tx.input[i].witness.push(ser_sig);
// Due to BIP146 (MINIMALIF) this must be a zero-length element to relay.
bumped_tx.input[i].witness.push(vec![]);
bumped_tx.input[i].witness.push(witness_script.clone().into_bytes());
}
},
_ => { panic!("API Error!"); }
}
true
}
fn get_maybe_finalized_tx<Signer: EcdsaChannelSigner>(&self, outpoint: &BitcoinOutPoint, onchain_handler: &mut OnchainTxHandler<Signer>) -> Option<MaybeSignedTransaction> {
match self {
PackageSolvingData::HolderHTLCOutput(ref outp) => {
debug_assert!(!outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
onchain_handler.get_maybe_signed_htlc_tx(outpoint, &outp.preimage)
}
PackageSolvingData::HolderFundingOutput(ref outp) => {
Some(onchain_handler.get_maybe_signed_holder_tx(&outp.funding_redeemscript))
}
_ => { panic!("API Error!"); }
}
}
/// Some output types are locked with CHECKLOCKTIMEVERIFY and the spending transaction must
/// have a minimum locktime, which is returned here.
fn minimum_locktime(&self) -> Option<u32> {
match self {
PackageSolvingData::CounterpartyReceivedHTLCOutput(ref outp) => Some(outp.htlc.cltv_expiry),
_ => None,
}
}
/// Some output types are pre-signed in such a way that the spending transaction must have an
/// exact locktime. This returns that locktime for such outputs.
fn signed_locktime(&self) -> Option<u32> {
match self {
PackageSolvingData::HolderHTLCOutput(ref outp) => {
if outp.preimage.is_some() {
debug_assert_eq!(outp.cltv_expiry, 0);
}
Some(outp.cltv_expiry)
},
_ => None,
}
}
fn map_output_type_flags(&self) -> PackageMalleability {
// We classify claims into not-mergeable (i.e. transactions that have to be broadcasted
// as-is) or merge-able (i.e. transactions we can merge with others and claim in batches),
// which we then sub-categorize into pinnable (where our counterparty could potentially
// also claim the transaction right now) or unpinnable (where only we can claim this
// output). We assume we are claiming in a timely manner.
match self {
PackageSolvingData::RevokedOutput(RevokedOutput { .. }) =>
PackageMalleability::Malleable(AggregationCluster::Unpinnable),
PackageSolvingData::RevokedHTLCOutput(..) =>
PackageMalleability::Malleable(AggregationCluster::Pinnable),
PackageSolvingData::CounterpartyOfferedHTLCOutput(..) =>
PackageMalleability::Malleable(AggregationCluster::Unpinnable),
PackageSolvingData::CounterpartyReceivedHTLCOutput(..) =>
PackageMalleability::Malleable(AggregationCluster::Pinnable),
PackageSolvingData::HolderHTLCOutput(ref outp) if outp.channel_type_features.supports_anchors_zero_fee_htlc_tx() => {
if outp.preimage.is_some() {
PackageMalleability::Malleable(AggregationCluster::Unpinnable)
} else {
PackageMalleability::Malleable(AggregationCluster::Pinnable)
}
},
PackageSolvingData::HolderHTLCOutput(..) => PackageMalleability::Untractable,
PackageSolvingData::HolderFundingOutput(..) => PackageMalleability::Untractable,
}
}
}
impl_writeable_tlv_based_enum_legacy!(PackageSolvingData, ;
(0, RevokedOutput),
(1, RevokedHTLCOutput),
(2, CounterpartyOfferedHTLCOutput),
(3, CounterpartyReceivedHTLCOutput),
(4, HolderHTLCOutput),
(5, HolderFundingOutput),
);
/// We aggregate claims into clusters based on if we think the output is potentially pinnable by
/// our counterparty and whether the CLTVs required make sense to aggregate into one claim.
/// That way we avoid claiming in too many discrete transactions while also avoiding
/// unnecessarily exposing ourselves to pinning attacks or delaying claims when we could have
/// claimed at least part of the available outputs quickly and without risk.
#[derive(Copy, Clone, PartialEq, Eq)]
enum AggregationCluster {
/// Our counterparty can potentially claim this output.
Pinnable,
/// We are the only party that can claim these funds, thus we believe they are not pinnable
/// until they reach a CLTV/CSV expiry where our counterparty could also claim them.
Unpinnable,
}
/// A malleable package might be aggregated with other packages to save on fees.
/// A untractable package has been counter-signed and aggregable will break cached counterparty signatures.
#[derive(Copy, Clone, PartialEq, Eq)]
enum PackageMalleability {
Malleable(AggregationCluster),
Untractable,
}
/// A structure to describe a package content that is generated by ChannelMonitor and
/// used by OnchainTxHandler to generate and broadcast transactions settling onchain claims.
///
/// A package is defined as one or more transactions claiming onchain outputs in reaction
/// to confirmation of a channel transaction. Those packages might be aggregated to save on
/// fees, if satisfaction of outputs's witnessScript let's us do so.
///
/// As packages are time-sensitive, we fee-bump and rebroadcast them at scheduled intervals.
/// Failing to confirm a package translate as a loss of funds for the user.
#[derive(Clone, PartialEq, Eq)]
pub struct PackageTemplate {
// List of onchain outputs and solving data to generate satisfying witnesses.
inputs: Vec<(BitcoinOutPoint, PackageSolvingData)>,
// Packages are deemed as malleable if we have local knwoledge of at least one set of
// private keys yielding a satisfying witnesses. Malleability implies that we can aggregate
// packages among them to save on fees or rely on RBF to bump their feerates.
// Untractable packages have been counter-signed and thus imply that we can't aggregate
// them without breaking signatures. Fee-bumping strategy will also rely on CPFP.
malleability: PackageMalleability,
/// Block height at which our counterparty can potentially claim this output as well (assuming
/// they have the keys or information required to do so).
///
/// This is used primarily by external consumers to decide when an output becomes "pinnable"
/// because the counterparty can potentially spend it. It is also used internally by
/// [`Self::get_height_timer`] to identify when an output must be claimed by, depending on the
/// type of output.
counterparty_spendable_height: u32,
// Cache of package feerate committed at previous (re)broadcast. If bumping resources
// (either claimed output value or external utxo), it will keep increasing until holder
// or counterparty successful claim.
feerate_previous: u64,
// Cache of next height at which fee-bumping and rebroadcast will be attempted. In
// the future, we might abstract it to an observed mempool fluctuation.
height_timer: u32,
}
impl PackageTemplate {
pub(crate) fn can_merge_with(&self, other: &PackageTemplate, cur_height: u32) -> bool {
match (self.malleability, other.malleability) {
(PackageMalleability::Untractable, _) => false,
(_, PackageMalleability::Untractable) => false,
(PackageMalleability::Malleable(self_cluster), PackageMalleability::Malleable(other_cluster)) => {
if self.inputs.is_empty() {
return false;
}
if other.inputs.is_empty() {
return false;
}
// First check the types of the inputs and don't merge if they are possibly claiming
// from different commitment transactions at the same time.
// This shouldn't ever happen, but if we do end up with packages trying to claim
// funds from two different commitment transactions (which cannot possibly be
// on-chain at the same time), we definitely shouldn't merge them.
#[cfg(debug_assertions)]
{
for i in 0..self.inputs.len() {
for j in 0..i {
debug_assert!(self.inputs[i].1.is_possibly_from_same_tx_tree(&self.inputs[j].1));
}
}
for i in 0..other.inputs.len() {
for j in 0..i {
assert!(other.inputs[i].1.is_possibly_from_same_tx_tree(&other.inputs[j].1));
}
}
}
if !self.inputs[0].1.is_possibly_from_same_tx_tree(&other.inputs[0].1) {
debug_assert!(false, "We shouldn't have packages from different tx trees");
return false;
}
// Check if the packages have signed locktimes. If they do, we only want to aggregate
// packages with the same, signed locktime.
if self.signed_locktime() != other.signed_locktime() {
return false;
}
// Check if the two packages have compatible minimum locktimes.
if self.package_locktime(cur_height) != other.package_locktime(cur_height) {
return false;
}
// Now check that we only merge packages if they are both unpinnable or both
// pinnable.
let self_pinnable = self_cluster == AggregationCluster::Pinnable ||
self.counterparty_spendable_height() <= cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
let other_pinnable = other_cluster == AggregationCluster::Pinnable ||
other.counterparty_spendable_height() <= cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
if self_pinnable && other_pinnable {
return true;
}
let self_unpinnable = self_cluster == AggregationCluster::Unpinnable &&
self.counterparty_spendable_height() > cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
let other_unpinnable = other_cluster == AggregationCluster::Unpinnable &&
other.counterparty_spendable_height() > cur_height + COUNTERPARTY_CLAIMABLE_WITHIN_BLOCKS_PINNABLE;
if self_unpinnable && other_unpinnable {
return true;
}
false
},
}
}
pub(crate) fn is_malleable(&self) -> bool {
matches!(self.malleability, PackageMalleability::Malleable(..))
}
/// The height at which our counterparty may be able to spend this output.
///
/// This is an important limit for aggregation as after this height our counterparty may be
/// able to pin transactions spending this output in the mempool.
pub(crate) fn counterparty_spendable_height(&self) -> u32 {
self.counterparty_spendable_height
}
pub(crate) fn previous_feerate(&self) -> u64 {
self.feerate_previous
}
pub(crate) fn set_feerate(&mut self, new_feerate: u64) {
self.feerate_previous = new_feerate;
}
pub(crate) fn timer(&self) -> u32 {
self.height_timer
}
pub(crate) fn set_timer(&mut self, new_timer: u32) {
self.height_timer = new_timer;
}
pub(crate) fn outpoints(&self) -> Vec<&BitcoinOutPoint> {
self.inputs.iter().map(|(o, _)| o).collect()
}
pub(crate) fn inputs(&self) -> impl ExactSizeIterator<Item = &PackageSolvingData> {
self.inputs.iter().map(|(_, i)| i)
}
pub(crate) fn split_package(&mut self, split_outp: &BitcoinOutPoint) -> Option<PackageTemplate> {
match self.malleability {
PackageMalleability::Malleable(cluster) => {
let mut split_package = None;
let feerate_previous = self.feerate_previous;
let height_timer = self.height_timer;
self.inputs.retain(|outp| {
if *split_outp == outp.0 {
split_package = Some(PackageTemplate {
inputs: vec![(outp.0, outp.1.clone())],
malleability: PackageMalleability::Malleable(cluster),
counterparty_spendable_height: self.counterparty_spendable_height,
feerate_previous,
height_timer,
});
return false;
}
return true;
});
return split_package;
},
_ => {
// Note, we may try to split on remote transaction for
// which we don't have a competing one (HTLC-Success before
// timelock expiration). This explain we don't panic!
// We should refactor OnchainTxHandler::block_connected to
// only test equality on competing claims.
return None;
}
}
}
pub(crate) fn merge_package(&mut self, mut merge_from: PackageTemplate, cur_height: u32) -> Result<(), PackageTemplate> {
if !self.can_merge_with(&merge_from, cur_height) {
return Err(merge_from);
}
for (k, v) in merge_from.inputs.drain(..) {
self.inputs.push((k, v));
}
//TODO: verify coverage and sanity?
if self.counterparty_spendable_height > merge_from.counterparty_spendable_height {
self.counterparty_spendable_height = merge_from.counterparty_spendable_height;
}
if self.feerate_previous > merge_from.feerate_previous {
self.feerate_previous = merge_from.feerate_previous;
}
self.height_timer = cmp::min(self.height_timer, merge_from.height_timer);
Ok(())
}
/// Gets the amount of all outptus being spent by this package, only valid for malleable
/// packages.
pub(crate) fn package_amount(&self) -> u64 {
let mut amounts = 0;
for (_, outp) in self.inputs.iter() {
amounts += outp.amount();
}
amounts
}
fn signed_locktime(&self) -> Option<u32> {
let signed_locktime = self.inputs.iter().find_map(|(_, outp)| outp.signed_locktime());
#[cfg(debug_assertions)]
for (_, outp) in &self.inputs {
debug_assert!(outp.signed_locktime().is_none() || outp.signed_locktime() == signed_locktime);
}
signed_locktime
}
pub(crate) fn package_locktime(&self, current_height: u32) -> u32 {
let minimum_locktime = self.inputs.iter().filter_map(|(_, outp)| outp.minimum_locktime()).max();
if let Some(signed_locktime) = self.signed_locktime() {
debug_assert!(minimum_locktime.is_none());
signed_locktime
} else {
core::cmp::max(current_height, minimum_locktime.unwrap_or(0))
}
}
pub(crate) fn package_weight(&self, destination_script: &Script) -> u64 {
let mut inputs_weight = 0;
let mut witnesses_weight = 2; // count segwit flags
for (_, outp) in self.inputs.iter() {
// previous_out_point: 36 bytes ; var_int: 1 byte ; sequence: 4 bytes
inputs_weight += 41 * WITNESS_SCALE_FACTOR;
witnesses_weight += outp.weight();
}
// version: 4 bytes ; count_tx_in: 1 byte ; count_tx_out: 1 byte ; lock_time: 4 bytes
let transaction_weight = 10 * WITNESS_SCALE_FACTOR;
// value: 8 bytes ; var_int: 1 byte ; pk_script: `destination_script.len()`
let output_weight = (8 + 1 + destination_script.len()) * WITNESS_SCALE_FACTOR;
(inputs_weight + witnesses_weight + transaction_weight + output_weight) as u64
}
pub(crate) fn construct_malleable_package_with_external_funding<Signer: EcdsaChannelSigner>(
&self, onchain_handler: &mut OnchainTxHandler<Signer>,
) -> Option<Vec<ExternalHTLCClaim>> {
debug_assert!(self.requires_external_funding());
let mut htlcs: Option<Vec<ExternalHTLCClaim>> = None;
for (previous_output, input) in &self.inputs {
match input {
PackageSolvingData::HolderHTLCOutput(ref outp) => {
debug_assert!(outp.channel_type_features.supports_anchors_zero_fee_htlc_tx());
onchain_handler.generate_external_htlc_claim(&previous_output, &outp.preimage).map(|htlc| {
htlcs.get_or_insert_with(|| Vec::with_capacity(self.inputs.len())).push(htlc);
});
}
_ => debug_assert!(false, "Expected HolderHTLCOutputs to not be aggregated with other input types"),
}
}
htlcs
}
pub(crate) fn maybe_finalize_malleable_package<L: Logger, Signer: EcdsaChannelSigner>(
&self, current_height: u32, onchain_handler: &mut OnchainTxHandler<Signer>, value: Amount,
destination_script: ScriptBuf, logger: &L
) -> Option<MaybeSignedTransaction> {
debug_assert!(self.is_malleable());
let mut bumped_tx = Transaction {
version: Version::TWO,
lock_time: LockTime::from_consensus(self.package_locktime(current_height)),
input: vec![],
output: vec![TxOut {
script_pubkey: destination_script,