-
Notifications
You must be signed in to change notification settings - Fork 368
/
channel.rs
11918 lines (10638 loc) · 621 KB
/
channel.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.
use bitcoin::amount::Amount;
use bitcoin::constants::ChainHash;
use bitcoin::script::{Script, ScriptBuf, Builder, WScriptHash};
use bitcoin::transaction::{Transaction, TxIn};
use bitcoin::sighash;
use bitcoin::sighash::EcdsaSighashType;
use bitcoin::consensus::encode;
use bitcoin::absolute::LockTime;
use bitcoin::Weight;
use bitcoin::hashes::Hash;
use bitcoin::hashes::sha256::Hash as Sha256;
use bitcoin::hashes::sha256d::Hash as Sha256d;
use bitcoin::hash_types::{Txid, BlockHash};
use bitcoin::secp256k1::constants::PUBLIC_KEY_SIZE;
use bitcoin::secp256k1::{PublicKey,SecretKey};
use bitcoin::secp256k1::{Secp256k1,ecdsa::Signature};
use bitcoin::secp256k1;
use crate::ln::types::ChannelId;
use crate::types::payment::{PaymentPreimage, PaymentHash};
use crate::types::features::{ChannelTypeFeatures, InitFeatures};
use crate::ln::interactivetxs::{
get_output_weight, HandleTxCompleteValue, HandleTxCompleteResult, InteractiveTxConstructor,
InteractiveTxConstructorArgs, InteractiveTxSigningSession, InteractiveTxMessageSendResult,
TX_COMMON_FIELDS_WEIGHT,
};
use crate::ln::msgs;
use crate::ln::msgs::{ClosingSigned, ClosingSignedFeeRange, DecodeError};
use crate::ln::script::{self, ShutdownScript};
use crate::ln::channel_state::{ChannelShutdownState, CounterpartyForwardingInfo, InboundHTLCDetails, InboundHTLCStateDetails, OutboundHTLCDetails, OutboundHTLCStateDetails};
use crate::ln::channelmanager::{self, PendingHTLCStatus, HTLCSource, SentHTLCId, HTLCFailureMsg, PendingHTLCInfo, RAACommitmentOrder, PaymentClaimDetails, BREAKDOWN_TIMEOUT, MIN_CLTV_EXPIRY_DELTA, MAX_LOCAL_BREAKDOWN_TIMEOUT};
use crate::ln::chan_utils::{
CounterpartyCommitmentSecrets, TxCreationKeys, HTLCOutputInCommitment, htlc_success_tx_weight,
htlc_timeout_tx_weight, make_funding_redeemscript, ChannelPublicKeys, CommitmentTransaction,
HolderCommitmentTransaction, ChannelTransactionParameters,
CounterpartyChannelTransactionParameters, MAX_HTLCS,
get_commitment_transaction_number_obscure_factor,
ClosingTransaction, commit_tx_fee_sat, per_outbound_htlc_counterparty_commit_tx_fee_msat,
};
use crate::ln::chan_utils;
use crate::ln::onion_utils::HTLCFailReason;
use crate::chain::BestBlock;
use crate::chain::chaininterface::{FeeEstimator, ConfirmationTarget, LowerBoundedFeeEstimator, fee_for_weight};
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, LATENCY_GRACE_PERIOD_BLOCKS};
use crate::chain::transaction::{OutPoint, TransactionData};
use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::sign::{EntropySource, ChannelSigner, SignerProvider, NodeSigner, Recipient};
use crate::events::{ClosureReason, Event};
use crate::routing::gossip::NodeId;
use crate::util::ser::{Readable, ReadableArgs, TransactionU16LenLimited, Writeable, Writer};
use crate::util::logger::{Logger, Record, WithContext};
use crate::util::errors::APIError;
use crate::util::config::{UserConfig, ChannelConfig, LegacyChannelConfig, ChannelHandshakeConfig, ChannelHandshakeLimits, MaxDustHTLCExposure};
use crate::util::scid_utils::scid_from_parts;
use crate::io;
use crate::prelude::*;
use core::{cmp,mem,fmt};
use core::ops::Deref;
#[cfg(any(test, fuzzing, debug_assertions))]
use crate::sync::Mutex;
use crate::sign::type_resolver::ChannelSignerType;
use super::channel_keys::{DelayedPaymentBasepoint, HtlcBasepoint, RevocationBasepoint};
#[cfg(test)]
pub struct ChannelValueStat {
pub value_to_self_msat: u64,
pub channel_value_msat: u64,
pub channel_reserve_msat: u64,
pub pending_outbound_htlcs_amount_msat: u64,
pub pending_inbound_htlcs_amount_msat: u64,
pub holding_cell_outbound_amount_msat: u64,
pub counterparty_max_htlc_value_in_flight_msat: u64, // outgoing
pub counterparty_dust_limit_msat: u64,
}
pub struct AvailableBalances {
/// Total amount available for our counterparty to send to us.
pub inbound_capacity_msat: u64,
/// Total amount available for us to send to our counterparty.
pub outbound_capacity_msat: u64,
/// The maximum value we can assign to the next outbound HTLC
pub next_outbound_htlc_limit_msat: u64,
/// The minimum value we can assign to the next outbound HTLC
pub next_outbound_htlc_minimum_msat: u64,
}
#[derive(Debug, Clone, Copy, PartialEq)]
enum FeeUpdateState {
// Inbound states mirroring InboundHTLCState
RemoteAnnounced,
AwaitingRemoteRevokeToAnnounce,
// Note that we do not have a AwaitingAnnouncedRemoteRevoke variant here as it is universally
// handled the same as `Committed`, with the only exception in `InboundHTLCState` being the
// distinction of when we allow ourselves to forward the HTLC. Because we aren't "forwarding"
// the fee update anywhere, we can simply consider the fee update `Committed` immediately
// instead of setting it to AwaitingAnnouncedRemoteRevoke.
// Outbound state can only be `LocalAnnounced` or `Committed`
Outbound,
}
enum InboundHTLCRemovalReason {
FailRelay(msgs::OnionErrorPacket),
FailMalformed(([u8; 32], u16)),
Fulfill(PaymentPreimage),
}
/// Represents the resolution status of an inbound HTLC.
#[derive(Clone)]
enum InboundHTLCResolution {
/// Resolved implies the action we must take with the inbound HTLC has already been determined,
/// i.e., we already know whether it must be failed back or forwarded.
//
// TODO: Once this variant is removed, we should also clean up
// [`MonitorRestoreUpdates::accepted_htlcs`] as the path will be unreachable.
Resolved {
pending_htlc_status: PendingHTLCStatus,
},
/// Pending implies we will attempt to resolve the inbound HTLC once it has been fully committed
/// to by both sides of the channel, i.e., once a `revoke_and_ack` has been processed by both
/// nodes for the state update in which it was proposed.
Pending {
update_add_htlc: msgs::UpdateAddHTLC,
},
}
impl_writeable_tlv_based_enum!(InboundHTLCResolution,
(0, Resolved) => {
(0, pending_htlc_status, required),
},
(2, Pending) => {
(0, update_add_htlc, required),
},
);
enum InboundHTLCState {
/// Offered by remote, to be included in next local commitment tx. I.e., the remote sent an
/// update_add_htlc message for this HTLC.
RemoteAnnounced(InboundHTLCResolution),
/// Included in a received commitment_signed message (implying we've
/// revoke_and_ack'd it), but the remote hasn't yet revoked their previous
/// state (see the example below). We have not yet included this HTLC in a
/// commitment_signed message because we are waiting on the remote's
/// aforementioned state revocation. One reason this missing remote RAA
/// (revoke_and_ack) blocks us from constructing a commitment_signed message
/// is because every time we create a new "state", i.e. every time we sign a
/// new commitment tx (see [BOLT #2]), we need a new per_commitment_point,
/// which are provided one-at-a-time in each RAA. E.g., the last RAA they
/// sent provided the per_commitment_point for our current commitment tx.
/// The other reason we should not send a commitment_signed without their RAA
/// is because their RAA serves to ACK our previous commitment_signed.
///
/// Here's an example of how an HTLC could come to be in this state:
/// remote --> update_add_htlc(prev_htlc) --> local
/// remote --> commitment_signed(prev_htlc) --> local
/// remote <-- revoke_and_ack <-- local
/// remote <-- commitment_signed(prev_htlc) <-- local
/// [note that here, the remote does not respond with a RAA]
/// remote --> update_add_htlc(this_htlc) --> local
/// remote --> commitment_signed(prev_htlc, this_htlc) --> local
/// Now `this_htlc` will be assigned this state. It's unable to be officially
/// accepted, i.e. included in a commitment_signed, because we're missing the
/// RAA that provides our next per_commitment_point. The per_commitment_point
/// is used to derive commitment keys, which are used to construct the
/// signatures in a commitment_signed message.
/// Implies AwaitingRemoteRevoke.
///
/// [BOLT #2]: https://github.com/lightning/bolts/blob/master/02-peer-protocol.md
AwaitingRemoteRevokeToAnnounce(InboundHTLCResolution),
/// Included in a received commitment_signed message (implying we've revoke_and_ack'd it).
/// We have also included this HTLC in our latest commitment_signed and are now just waiting
/// on the remote's revoke_and_ack to make this HTLC an irrevocable part of the state of the
/// channel (before it can then get forwarded and/or removed).
/// Implies AwaitingRemoteRevoke.
AwaitingAnnouncedRemoteRevoke(InboundHTLCResolution),
Committed,
/// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we
/// created it we would have put it in the holding cell instead). When they next revoke_and_ack
/// we'll drop it.
/// Note that we have to keep an eye on the HTLC until we've received a broadcastable
/// commitment transaction without it as otherwise we'll have to force-close the channel to
/// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim
/// anyway). That said, ChannelMonitor does this for us (see
/// ChannelMonitor::should_broadcast_holder_commitment_txn) so we actually remove the HTLC from
/// our own local state before then, once we're sure that the next commitment_signed and
/// ChannelMonitor::provide_latest_local_commitment_tx will not include this HTLC.
LocalRemoved(InboundHTLCRemovalReason),
}
impl From<&InboundHTLCState> for Option<InboundHTLCStateDetails> {
fn from(state: &InboundHTLCState) -> Option<InboundHTLCStateDetails> {
match state {
InboundHTLCState::RemoteAnnounced(_) => None,
InboundHTLCState::AwaitingRemoteRevokeToAnnounce(_) =>
Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToAdd),
InboundHTLCState::AwaitingAnnouncedRemoteRevoke(_) =>
Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToAdd),
InboundHTLCState::Committed =>
Some(InboundHTLCStateDetails::Committed),
InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailRelay(_)) =>
Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail),
InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::FailMalformed(_)) =>
Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFail),
InboundHTLCState::LocalRemoved(InboundHTLCRemovalReason::Fulfill(_)) =>
Some(InboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFulfill),
}
}
}
struct InboundHTLCOutput {
htlc_id: u64,
amount_msat: u64,
cltv_expiry: u32,
payment_hash: PaymentHash,
state: InboundHTLCState,
}
#[cfg_attr(test, derive(Clone, Debug, PartialEq))]
enum OutboundHTLCState {
/// Added by us and included in a commitment_signed (if we were AwaitingRemoteRevoke when we
/// created it we would have put it in the holding cell instead). When they next revoke_and_ack
/// we will promote to Committed (note that they may not accept it until the next time we
/// revoke, but we don't really care about that:
/// * they've revoked, so worst case we can announce an old state and get our (option on)
/// money back (though we won't), and,
/// * we'll send them a revoke when they send a commitment_signed, and since only they're
/// allowed to remove it, the "can only be removed once committed on both sides" requirement
/// doesn't matter to us and it's up to them to enforce it, worst-case they jump ahead but
/// we'll never get out of sync).
/// Note that we Box the OnionPacket as it's rather large and we don't want to blow up
/// OutboundHTLCOutput's size just for a temporary bit
LocalAnnounced(Box<msgs::OnionPacket>),
Committed,
/// Remote removed this (outbound) HTLC. We're waiting on their commitment_signed to finalize
/// the change (though they'll need to revoke before we fail the payment).
RemoteRemoved(OutboundHTLCOutcome),
/// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but
/// the remote side hasn't yet revoked their previous state, which we need them to do before we
/// can do any backwards failing. Implies AwaitingRemoteRevoke.
/// We also have not yet removed this HTLC in a commitment_signed message, and are waiting on a
/// remote revoke_and_ack on a previous state before we can do so.
AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome),
/// Remote removed this and sent a commitment_signed (implying we've revoke_and_ack'ed it), but
/// the remote side hasn't yet revoked their previous state, which we need them to do before we
/// can do any backwards failing. Implies AwaitingRemoteRevoke.
/// We have removed this HTLC in our latest commitment_signed and are now just waiting on a
/// revoke_and_ack to drop completely.
AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome),
}
impl From<&OutboundHTLCState> for OutboundHTLCStateDetails {
fn from(state: &OutboundHTLCState) -> OutboundHTLCStateDetails {
match state {
OutboundHTLCState::LocalAnnounced(_) =>
OutboundHTLCStateDetails::AwaitingRemoteRevokeToAdd,
OutboundHTLCState::Committed =>
OutboundHTLCStateDetails::Committed,
// RemoteRemoved states are ignored as the state is transient and the remote has not committed to
// the state yet.
OutboundHTLCState::RemoteRemoved(_) =>
OutboundHTLCStateDetails::Committed,
OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Success(_)) =>
OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveSuccess,
OutboundHTLCState::AwaitingRemoteRevokeToRemove(OutboundHTLCOutcome::Failure(_)) =>
OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFailure,
OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Success(_)) =>
OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveSuccess,
OutboundHTLCState::AwaitingRemovedRemoteRevoke(OutboundHTLCOutcome::Failure(_)) =>
OutboundHTLCStateDetails::AwaitingRemoteRevokeToRemoveFailure,
}
}
}
#[derive(Clone)]
#[cfg_attr(test, derive(Debug, PartialEq))]
enum OutboundHTLCOutcome {
/// LDK version 0.0.105+ will always fill in the preimage here.
Success(Option<PaymentPreimage>),
Failure(HTLCFailReason),
}
impl From<Option<HTLCFailReason>> for OutboundHTLCOutcome {
fn from(o: Option<HTLCFailReason>) -> Self {
match o {
None => OutboundHTLCOutcome::Success(None),
Some(r) => OutboundHTLCOutcome::Failure(r)
}
}
}
impl<'a> Into<Option<&'a HTLCFailReason>> for &'a OutboundHTLCOutcome {
fn into(self) -> Option<&'a HTLCFailReason> {
match self {
OutboundHTLCOutcome::Success(_) => None,
OutboundHTLCOutcome::Failure(ref r) => Some(r)
}
}
}
#[cfg_attr(test, derive(Clone, Debug, PartialEq))]
struct OutboundHTLCOutput {
htlc_id: u64,
amount_msat: u64,
cltv_expiry: u32,
payment_hash: PaymentHash,
state: OutboundHTLCState,
source: HTLCSource,
blinding_point: Option<PublicKey>,
skimmed_fee_msat: Option<u64>,
}
/// See AwaitingRemoteRevoke ChannelState for more info
#[cfg_attr(test, derive(Clone, Debug, PartialEq))]
enum HTLCUpdateAwaitingACK {
AddHTLC { // TODO: Time out if we're getting close to cltv_expiry
// always outbound
amount_msat: u64,
cltv_expiry: u32,
payment_hash: PaymentHash,
source: HTLCSource,
onion_routing_packet: msgs::OnionPacket,
// The extra fee we're skimming off the top of this HTLC.
skimmed_fee_msat: Option<u64>,
blinding_point: Option<PublicKey>,
},
ClaimHTLC {
payment_preimage: PaymentPreimage,
htlc_id: u64,
},
FailHTLC {
htlc_id: u64,
err_packet: msgs::OnionErrorPacket,
},
FailMalformedHTLC {
htlc_id: u64,
failure_code: u16,
sha256_of_onion: [u8; 32],
},
}
macro_rules! define_state_flags {
($flag_type_doc: expr, $flag_type: ident, [$(($flag_doc: expr, $flag: ident, $value: expr, $get: ident, $set: ident, $clear: ident)),+], $extra_flags: expr) => {
#[doc = $flag_type_doc]
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq)]
struct $flag_type(u32);
impl $flag_type {
$(
#[doc = $flag_doc]
const $flag: $flag_type = $flag_type($value);
)*
/// All flags that apply to the specified [`ChannelState`] variant.
#[allow(unused)]
const ALL: $flag_type = Self($(Self::$flag.0 | )* $extra_flags);
#[allow(unused)]
fn new() -> Self { Self(0) }
#[allow(unused)]
fn from_u32(flags: u32) -> Result<Self, ()> {
if flags & !Self::ALL.0 != 0 {
Err(())
} else {
Ok($flag_type(flags))
}
}
#[allow(unused)]
fn is_empty(&self) -> bool { self.0 == 0 }
#[allow(unused)]
fn is_set(&self, flag: Self) -> bool { *self & flag == flag }
#[allow(unused)]
fn set(&mut self, flag: Self) { *self |= flag }
#[allow(unused)]
fn clear(&mut self, flag: Self) -> Self { self.0 &= !flag.0; *self }
}
$(
define_state_flags!($flag_type, Self::$flag, $get, $set, $clear);
)*
impl core::ops::BitOr for $flag_type {
type Output = Self;
fn bitor(self, rhs: Self) -> Self::Output { Self(self.0 | rhs.0) }
}
impl core::ops::BitOrAssign for $flag_type {
fn bitor_assign(&mut self, rhs: Self) { self.0 |= rhs.0; }
}
impl core::ops::BitAnd for $flag_type {
type Output = Self;
fn bitand(self, rhs: Self) -> Self::Output { Self(self.0 & rhs.0) }
}
impl core::ops::BitAndAssign for $flag_type {
fn bitand_assign(&mut self, rhs: Self) { self.0 &= rhs.0; }
}
};
($flag_type_doc: expr, $flag_type: ident, $flags: tt) => {
define_state_flags!($flag_type_doc, $flag_type, $flags, 0);
};
($flag_type: ident, $flag: expr, $get: ident, $set: ident, $clear: ident) => {
impl $flag_type {
#[allow(unused)]
fn $get(&self) -> bool { self.is_set($flag_type::new() | $flag) }
#[allow(unused)]
fn $set(&mut self) { self.set($flag_type::new() | $flag) }
#[allow(unused)]
fn $clear(&mut self) -> Self { self.clear($flag_type::new() | $flag) }
}
};
($flag_type_doc: expr, FUNDED_STATE, $flag_type: ident, $flags: tt) => {
define_state_flags!($flag_type_doc, $flag_type, $flags, FundedStateFlags::ALL.0);
define_state_flags!($flag_type, FundedStateFlags::PEER_DISCONNECTED,
is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected);
define_state_flags!($flag_type, FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS,
is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress);
define_state_flags!($flag_type, FundedStateFlags::REMOTE_SHUTDOWN_SENT,
is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent);
define_state_flags!($flag_type, FundedStateFlags::LOCAL_SHUTDOWN_SENT,
is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent);
impl core::ops::BitOr<FundedStateFlags> for $flag_type {
type Output = Self;
fn bitor(self, rhs: FundedStateFlags) -> Self::Output { Self(self.0 | rhs.0) }
}
impl core::ops::BitOrAssign<FundedStateFlags> for $flag_type {
fn bitor_assign(&mut self, rhs: FundedStateFlags) { self.0 |= rhs.0; }
}
impl core::ops::BitAnd<FundedStateFlags> for $flag_type {
type Output = Self;
fn bitand(self, rhs: FundedStateFlags) -> Self::Output { Self(self.0 & rhs.0) }
}
impl core::ops::BitAndAssign<FundedStateFlags> for $flag_type {
fn bitand_assign(&mut self, rhs: FundedStateFlags) { self.0 &= rhs.0; }
}
impl PartialEq<FundedStateFlags> for $flag_type {
fn eq(&self, other: &FundedStateFlags) -> bool { self.0 == other.0 }
}
impl From<FundedStateFlags> for $flag_type {
fn from(flags: FundedStateFlags) -> Self { Self(flags.0) }
}
};
}
/// We declare all the states/flags here together to help determine which bits are still available
/// to choose.
mod state_flags {
pub const OUR_INIT_SENT: u32 = 1 << 0;
pub const THEIR_INIT_SENT: u32 = 1 << 1;
pub const FUNDING_NEGOTIATED: u32 = 1 << 2;
pub const AWAITING_CHANNEL_READY: u32 = 1 << 3;
pub const THEIR_CHANNEL_READY: u32 = 1 << 4;
pub const OUR_CHANNEL_READY: u32 = 1 << 5;
pub const CHANNEL_READY: u32 = 1 << 6;
pub const PEER_DISCONNECTED: u32 = 1 << 7;
pub const MONITOR_UPDATE_IN_PROGRESS: u32 = 1 << 8;
pub const AWAITING_REMOTE_REVOKE: u32 = 1 << 9;
pub const REMOTE_SHUTDOWN_SENT: u32 = 1 << 10;
pub const LOCAL_SHUTDOWN_SENT: u32 = 1 << 11;
pub const SHUTDOWN_COMPLETE: u32 = 1 << 12;
pub const WAITING_FOR_BATCH: u32 = 1 << 13;
}
define_state_flags!(
"Flags that apply to all [`ChannelState`] variants in which the channel is funded.",
FundedStateFlags, [
("Indicates the remote side is considered \"disconnected\" and no updates are allowed \
until after we've done a `channel_reestablish` dance.", PEER_DISCONNECTED, state_flags::PEER_DISCONNECTED,
is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected),
("Indicates the user has told us a `ChannelMonitor` update is pending async persistence \
somewhere and we should pause sending any outbound messages until they've managed to \
complete it.", MONITOR_UPDATE_IN_PROGRESS, state_flags::MONITOR_UPDATE_IN_PROGRESS,
is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress),
("Indicates we received a `shutdown` message from the remote end. If set, they may not add \
any new HTLCs to the channel, and we are expected to respond with our own `shutdown` \
message when possible.", REMOTE_SHUTDOWN_SENT, state_flags::REMOTE_SHUTDOWN_SENT,
is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent),
("Indicates we sent a `shutdown` message. At this point, we may not add any new HTLCs to \
the channel.", LOCAL_SHUTDOWN_SENT, state_flags::LOCAL_SHUTDOWN_SENT,
is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent)
]
);
define_state_flags!(
"Flags that only apply to [`ChannelState::NegotiatingFunding`].",
NegotiatingFundingFlags, [
("Indicates we have (or are prepared to) send our `open_channel`/`accept_channel` message.",
OUR_INIT_SENT, state_flags::OUR_INIT_SENT, is_our_init_sent, set_our_init_sent, clear_our_init_sent),
("Indicates we have received their `open_channel`/`accept_channel` message.",
THEIR_INIT_SENT, state_flags::THEIR_INIT_SENT, is_their_init_sent, set_their_init_sent, clear_their_init_sent)
]
);
define_state_flags!(
"Flags that only apply to [`ChannelState::AwaitingChannelReady`].",
FUNDED_STATE, AwaitingChannelReadyFlags, [
("Indicates they sent us a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \
`OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.",
THEIR_CHANNEL_READY, state_flags::THEIR_CHANNEL_READY,
is_their_channel_ready, set_their_channel_ready, clear_their_channel_ready),
("Indicates we sent them a `channel_ready` message. Once both `THEIR_CHANNEL_READY` and \
`OUR_CHANNEL_READY` are set, our state moves on to `ChannelReady`.",
OUR_CHANNEL_READY, state_flags::OUR_CHANNEL_READY,
is_our_channel_ready, set_our_channel_ready, clear_our_channel_ready),
("Indicates the channel was funded in a batch and the broadcast of the funding transaction \
is being held until all channels in the batch have received `funding_signed` and have \
their monitors persisted.", WAITING_FOR_BATCH, state_flags::WAITING_FOR_BATCH,
is_waiting_for_batch, set_waiting_for_batch, clear_waiting_for_batch)
]
);
define_state_flags!(
"Flags that only apply to [`ChannelState::ChannelReady`].",
FUNDED_STATE, ChannelReadyFlags, [
("Indicates that we have sent a `commitment_signed` but are awaiting the responding \
`revoke_and_ack` message. During this period, we can't generate new `commitment_signed` \
messages as we'd be unable to determine which HTLCs they included in their `revoke_and_ack` \
implicit ACK, so instead we have to hold them away temporarily to be sent later.",
AWAITING_REMOTE_REVOKE, state_flags::AWAITING_REMOTE_REVOKE,
is_awaiting_remote_revoke, set_awaiting_remote_revoke, clear_awaiting_remote_revoke)
]
);
// Note that the order of this enum is implicitly defined by where each variant is placed. Take this
// into account when introducing new states and update `test_channel_state_order` accordingly.
#[derive(Copy, Clone, Debug, PartialEq, PartialOrd, Eq)]
enum ChannelState {
/// We are negotiating the parameters required for the channel prior to funding it.
NegotiatingFunding(NegotiatingFundingFlags),
/// We have sent `funding_created` and are awaiting a `funding_signed` to advance to
/// `AwaitingChannelReady`. Note that this is nonsense for an inbound channel as we immediately generate
/// `funding_signed` upon receipt of `funding_created`, so simply skip this state.
FundingNegotiated,
/// We've received/sent `funding_created` and `funding_signed` and are thus now waiting on the
/// funding transaction to confirm.
AwaitingChannelReady(AwaitingChannelReadyFlags),
/// Both we and our counterparty consider the funding transaction confirmed and the channel is
/// now operational.
ChannelReady(ChannelReadyFlags),
/// We've successfully negotiated a `closing_signed` dance. At this point, the `ChannelManager`
/// is about to drop us, but we store this anyway.
ShutdownComplete,
}
macro_rules! impl_state_flag {
($get: ident, $set: ident, $clear: ident, [$($state: ident),+]) => {
#[allow(unused)]
fn $get(&self) -> bool {
match self {
$(
ChannelState::$state(flags) => flags.$get(),
)*
_ => false,
}
}
#[allow(unused)]
fn $set(&mut self) {
match self {
$(
ChannelState::$state(flags) => flags.$set(),
)*
_ => debug_assert!(false, "Attempted to set flag on unexpected ChannelState"),
}
}
#[allow(unused)]
fn $clear(&mut self) {
match self {
$(
ChannelState::$state(flags) => { let _ = flags.$clear(); },
)*
_ => debug_assert!(false, "Attempted to clear flag on unexpected ChannelState"),
}
}
};
($get: ident, $set: ident, $clear: ident, FUNDED_STATES) => {
impl_state_flag!($get, $set, $clear, [AwaitingChannelReady, ChannelReady]);
};
($get: ident, $set: ident, $clear: ident, $state: ident) => {
impl_state_flag!($get, $set, $clear, [$state]);
};
}
impl ChannelState {
fn from_u32(state: u32) -> Result<Self, ()> {
match state {
state_flags::FUNDING_NEGOTIATED => Ok(ChannelState::FundingNegotiated),
state_flags::SHUTDOWN_COMPLETE => Ok(ChannelState::ShutdownComplete),
val => {
if val & state_flags::AWAITING_CHANNEL_READY == state_flags::AWAITING_CHANNEL_READY {
AwaitingChannelReadyFlags::from_u32(val & !state_flags::AWAITING_CHANNEL_READY)
.map(|flags| ChannelState::AwaitingChannelReady(flags))
} else if val & state_flags::CHANNEL_READY == state_flags::CHANNEL_READY {
ChannelReadyFlags::from_u32(val & !state_flags::CHANNEL_READY)
.map(|flags| ChannelState::ChannelReady(flags))
} else if let Ok(flags) = NegotiatingFundingFlags::from_u32(val) {
Ok(ChannelState::NegotiatingFunding(flags))
} else {
Err(())
}
},
}
}
fn to_u32(self) -> u32 {
match self {
ChannelState::NegotiatingFunding(flags) => flags.0,
ChannelState::FundingNegotiated => state_flags::FUNDING_NEGOTIATED,
ChannelState::AwaitingChannelReady(flags) => state_flags::AWAITING_CHANNEL_READY | flags.0,
ChannelState::ChannelReady(flags) => state_flags::CHANNEL_READY | flags.0,
ChannelState::ShutdownComplete => state_flags::SHUTDOWN_COMPLETE,
}
}
fn is_pre_funded_state(&self) -> bool {
matches!(self, ChannelState::NegotiatingFunding(_)|ChannelState::FundingNegotiated)
}
fn is_both_sides_shutdown(&self) -> bool {
self.is_local_shutdown_sent() && self.is_remote_shutdown_sent()
}
fn with_funded_state_flags_mask(&self) -> FundedStateFlags {
match self {
ChannelState::AwaitingChannelReady(flags) => FundedStateFlags((*flags & FundedStateFlags::ALL).0),
ChannelState::ChannelReady(flags) => FundedStateFlags((*flags & FundedStateFlags::ALL).0),
_ => FundedStateFlags::new(),
}
}
fn can_generate_new_commitment(&self) -> bool {
match self {
ChannelState::ChannelReady(flags) =>
!flags.is_set(ChannelReadyFlags::AWAITING_REMOTE_REVOKE) &&
!flags.is_set(FundedStateFlags::MONITOR_UPDATE_IN_PROGRESS.into()) &&
!flags.is_set(FundedStateFlags::PEER_DISCONNECTED.into()),
_ => {
debug_assert!(false, "Can only generate new commitment within ChannelReady");
false
},
}
}
impl_state_flag!(is_peer_disconnected, set_peer_disconnected, clear_peer_disconnected, FUNDED_STATES);
impl_state_flag!(is_monitor_update_in_progress, set_monitor_update_in_progress, clear_monitor_update_in_progress, FUNDED_STATES);
impl_state_flag!(is_local_shutdown_sent, set_local_shutdown_sent, clear_local_shutdown_sent, FUNDED_STATES);
impl_state_flag!(is_remote_shutdown_sent, set_remote_shutdown_sent, clear_remote_shutdown_sent, FUNDED_STATES);
impl_state_flag!(is_our_channel_ready, set_our_channel_ready, clear_our_channel_ready, AwaitingChannelReady);
impl_state_flag!(is_their_channel_ready, set_their_channel_ready, clear_their_channel_ready, AwaitingChannelReady);
impl_state_flag!(is_waiting_for_batch, set_waiting_for_batch, clear_waiting_for_batch, AwaitingChannelReady);
impl_state_flag!(is_awaiting_remote_revoke, set_awaiting_remote_revoke, clear_awaiting_remote_revoke, ChannelReady);
}
pub const INITIAL_COMMITMENT_NUMBER: u64 = (1 << 48) - 1;
pub const DEFAULT_MAX_HTLCS: u16 = 50;
pub const ANCHOR_OUTPUT_VALUE_SATOSHI: u64 = 330;
/// The percentage of the channel value `holder_max_htlc_value_in_flight_msat` used to be set to,
/// before this was made configurable. The percentage was made configurable in LDK 0.0.107,
/// although LDK 0.0.104+ enabled serialization of channels with a different value set for
/// `holder_max_htlc_value_in_flight_msat`.
pub const MAX_IN_FLIGHT_PERCENT_LEGACY: u8 = 10;
/// Maximum `funding_satoshis` value according to the BOLT #2 specification, if
/// `option_support_large_channel` (aka wumbo channels) is not supported.
/// It's 2^24 - 1.
pub const MAX_FUNDING_SATOSHIS_NO_WUMBO: u64 = (1 << 24) - 1;
/// Total bitcoin supply in satoshis.
pub const TOTAL_BITCOIN_SUPPLY_SATOSHIS: u64 = 21_000_000 * 1_0000_0000;
/// The maximum network dust limit for standard script formats. This currently represents the
/// minimum output value for a P2SH output before Bitcoin Core 22 considers the entire
/// transaction non-standard and thus refuses to relay it.
/// We also use this as the maximum counterparty `dust_limit_satoshis` allowed, given many
/// implementations use this value for their dust limit today.
pub const MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS: u64 = 546;
/// The maximum channel dust limit we will accept from our counterparty.
pub const MAX_CHAN_DUST_LIMIT_SATOSHIS: u64 = MAX_STD_OUTPUT_DUST_LIMIT_SATOSHIS;
/// The dust limit is used for both the commitment transaction outputs as well as the closing
/// transactions. For cooperative closing transactions, we require segwit outputs, though accept
/// *any* segwit scripts, which are allowed to be up to 42 bytes in length.
/// In order to avoid having to concern ourselves with standardness during the closing process, we
/// simply require our counterparty to use a dust limit which will leave any segwit output
/// standard.
/// See <https://github.com/lightning/bolts/issues/905> for more details.
pub const MIN_CHAN_DUST_LIMIT_SATOSHIS: u64 = 354;
// Just a reasonable implementation-specific safe lower bound, higher than the dust limit.
pub const MIN_THEIR_CHAN_RESERVE_SATOSHIS: u64 = 1000;
/// Used to return a simple Error back to ChannelManager. Will get converted to a
/// msgs::ErrorAction::SendErrorMessage or msgs::ErrorAction::IgnoreError as appropriate with our
/// channel_id in ChannelManager.
pub(super) enum ChannelError {
Ignore(String),
Warn(String),
Close((String, ClosureReason)),
}
impl fmt::Debug for ChannelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ChannelError::Ignore(ref e) => write!(f, "Ignore : {}", e),
&ChannelError::Warn(ref e) => write!(f, "Warn : {}", e),
&ChannelError::Close((ref e, _)) => write!(f, "Close : {}", e),
}
}
}
impl fmt::Display for ChannelError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
&ChannelError::Ignore(ref e) => write!(f, "{}", e),
&ChannelError::Warn(ref e) => write!(f, "{}", e),
&ChannelError::Close((ref e, _)) => write!(f, "{}", e),
}
}
}
impl ChannelError {
pub(super) fn close(err: String) -> Self {
ChannelError::Close((err.clone(), ClosureReason::ProcessingError { err }))
}
}
pub(super) struct WithChannelContext<'a, L: Deref> where L::Target: Logger {
pub logger: &'a L,
pub peer_id: Option<PublicKey>,
pub channel_id: Option<ChannelId>,
pub payment_hash: Option<PaymentHash>,
}
impl<'a, L: Deref> Logger for WithChannelContext<'a, L> where L::Target: Logger {
fn log(&self, mut record: Record) {
record.peer_id = self.peer_id;
record.channel_id = self.channel_id;
record.payment_hash = self.payment_hash;
self.logger.log(record)
}
}
impl<'a, 'b, L: Deref> WithChannelContext<'a, L>
where L::Target: Logger {
pub(super) fn from<S: Deref>(logger: &'a L, context: &'b ChannelContext<S>, payment_hash: Option<PaymentHash>) -> Self
where S::Target: SignerProvider
{
WithChannelContext {
logger,
peer_id: Some(context.counterparty_node_id),
channel_id: Some(context.channel_id),
payment_hash
}
}
}
macro_rules! secp_check {
($res: expr, $err: expr) => {
match $res {
Ok(thing) => thing,
Err(_) => return Err(ChannelError::close($err)),
}
};
}
/// The "channel disabled" bit in channel_update must be set based on whether we are connected to
/// our counterparty or not. However, we don't want to announce updates right away to avoid
/// spamming the network with updates if the connection is flapping. Instead, we "stage" updates to
/// our channel_update message and track the current state here.
/// See implementation at [`super::channelmanager::ChannelManager::timer_tick_occurred`].
#[derive(Clone, Copy, PartialEq)]
pub(super) enum ChannelUpdateStatus {
/// We've announced the channel as enabled and are connected to our peer.
Enabled,
/// Our channel is no longer live, but we haven't announced the channel as disabled yet.
DisabledStaged(u8),
/// Our channel is live again, but we haven't announced the channel as enabled yet.
EnabledStaged(u8),
/// We've announced the channel as disabled.
Disabled,
}
/// We track when we sent an `AnnouncementSignatures` to our peer in a few states, described here.
#[derive(PartialEq)]
pub enum AnnouncementSigsState {
/// We have not sent our peer an `AnnouncementSignatures` yet, or our peer disconnected since
/// we sent the last `AnnouncementSignatures`.
NotSent,
/// We sent an `AnnouncementSignatures` to our peer since the last time our peer disconnected.
/// This state never appears on disk - instead we write `NotSent`.
MessageSent,
/// We sent a `CommitmentSigned` after the last `AnnouncementSignatures` we sent. Because we
/// only ever have a single `CommitmentSigned` pending at once, if we sent one after sending
/// `AnnouncementSignatures` then we know the peer received our `AnnouncementSignatures` if
/// they send back a `RevokeAndACK`.
/// This state never appears on disk - instead we write `NotSent`.
Committed,
/// We received a `RevokeAndACK`, effectively ack-ing our `AnnouncementSignatures`, at this
/// point we no longer need to re-send our `AnnouncementSignatures` again on reconnect.
PeerReceived,
}
/// An enum indicating whether the local or remote side offered a given HTLC.
enum HTLCInitiator {
LocalOffered,
RemoteOffered,
}
/// Current counts of various HTLCs, useful for calculating current balances available exactly.
struct HTLCStats {
pending_inbound_htlcs: usize,
pending_outbound_htlcs: usize,
pending_inbound_htlcs_value_msat: u64,
pending_outbound_htlcs_value_msat: u64,
on_counterparty_tx_dust_exposure_msat: u64,
on_holder_tx_dust_exposure_msat: u64,
outbound_holding_cell_msat: u64,
on_holder_tx_outbound_holding_cell_htlcs_count: u32, // dust HTLCs *non*-included
}
/// An enum gathering stats on commitment transaction, either local or remote.
struct CommitmentStats<'a> {
tx: CommitmentTransaction, // the transaction info
feerate_per_kw: u32, // the feerate included to build the transaction
total_fee_sat: u64, // the total fee included in the transaction
num_nondust_htlcs: usize, // the number of HTLC outputs (dust HTLCs *non*-included)
htlcs_included: Vec<(HTLCOutputInCommitment, Option<&'a HTLCSource>)>, // the list of HTLCs (dust HTLCs *included*) which were not ignored when building the transaction
local_balance_msat: u64, // local balance before fees *not* considering dust limits
remote_balance_msat: u64, // remote balance before fees *not* considering dust limits
outbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful offered HTLCs since last commitment
inbound_htlc_preimages: Vec<PaymentPreimage>, // preimages for successful received HTLCs since last commitment
}
/// Used when calculating whether we or the remote can afford an additional HTLC.
struct HTLCCandidate {
amount_msat: u64,
origin: HTLCInitiator,
}
impl HTLCCandidate {
fn new(amount_msat: u64, origin: HTLCInitiator) -> Self {
Self {
amount_msat,
origin,
}
}
}
/// A return value enum for get_update_fulfill_htlc. See UpdateFulfillCommitFetch variants for
/// description
enum UpdateFulfillFetch {
NewClaim {
monitor_update: ChannelMonitorUpdate,
htlc_value_msat: u64,
msg: Option<msgs::UpdateFulfillHTLC>,
},
DuplicateClaim {},
}
/// The return type of get_update_fulfill_htlc_and_commit.
pub enum UpdateFulfillCommitFetch {
/// Indicates the HTLC fulfill is new, and either generated an update_fulfill message, placed
/// it in the holding cell, or re-generated the update_fulfill message after the same claim was
/// previously placed in the holding cell (and has since been removed).
NewClaim {
/// The ChannelMonitorUpdate which places the new payment preimage in the channel monitor
monitor_update: ChannelMonitorUpdate,
/// The value of the HTLC which was claimed, in msat.
htlc_value_msat: u64,
},
/// Indicates the HTLC fulfill is duplicative and already existed either in the holding cell
/// or has been forgotten (presumably previously claimed).
DuplicateClaim {},
}
/// The return value of `monitor_updating_restored`
pub(super) struct MonitorRestoreUpdates {
pub raa: Option<msgs::RevokeAndACK>,
pub commitment_update: Option<msgs::CommitmentUpdate>,
pub order: RAACommitmentOrder,
pub accepted_htlcs: Vec<(PendingHTLCInfo, u64)>,
pub failed_htlcs: Vec<(HTLCSource, PaymentHash, HTLCFailReason)>,
pub finalized_claimed_htlcs: Vec<HTLCSource>,
pub pending_update_adds: Vec<msgs::UpdateAddHTLC>,
pub funding_broadcastable: Option<Transaction>,
pub channel_ready: Option<msgs::ChannelReady>,
pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
pub tx_signatures: Option<msgs::TxSignatures>,
}
/// The return value of `signer_maybe_unblocked`
#[allow(unused)]
pub(super) struct SignerResumeUpdates {
pub commitment_update: Option<msgs::CommitmentUpdate>,
pub revoke_and_ack: Option<msgs::RevokeAndACK>,
pub funding_signed: Option<msgs::FundingSigned>,
pub channel_ready: Option<msgs::ChannelReady>,
pub order: RAACommitmentOrder,
pub closing_signed: Option<msgs::ClosingSigned>,
pub signed_closing_tx: Option<Transaction>,
pub shutdown_result: Option<ShutdownResult>,
}
/// The return value of `channel_reestablish`
pub(super) struct ReestablishResponses {
pub channel_ready: Option<msgs::ChannelReady>,
pub raa: Option<msgs::RevokeAndACK>,
pub commitment_update: Option<msgs::CommitmentUpdate>,
pub order: RAACommitmentOrder,
pub announcement_sigs: Option<msgs::AnnouncementSignatures>,
pub shutdown_msg: Option<msgs::Shutdown>,
}
/// The result of a shutdown that should be handled.
#[must_use]
pub(crate) struct ShutdownResult {
pub(crate) closure_reason: ClosureReason,
/// A channel monitor update to apply.
pub(crate) monitor_update: Option<(PublicKey, OutPoint, ChannelId, ChannelMonitorUpdate)>,
/// A list of dropped outbound HTLCs that can safely be failed backwards immediately.
pub(crate) dropped_outbound_htlcs: Vec<(HTLCSource, PaymentHash, PublicKey, ChannelId)>,
/// An unbroadcasted batch funding transaction id. The closure of this channel should be
/// propagated to the remainder of the batch.
pub(crate) unbroadcasted_batch_funding_txid: Option<Txid>,
pub(crate) channel_id: ChannelId,
pub(crate) user_channel_id: u128,
pub(crate) channel_capacity_satoshis: u64,
pub(crate) counterparty_node_id: PublicKey,
pub(crate) is_manual_broadcast: bool,
pub(crate) unbroadcasted_funding_tx: Option<Transaction>,
pub(crate) channel_funding_txo: Option<OutPoint>,
pub(crate) last_local_balance_msat: u64,
}
/// Tracks the transaction number, along with current and next commitment points.
/// This consolidates the logic to advance our commitment number and request new
/// commitment points from our signer.
#[derive(Debug, Copy, Clone)]
enum HolderCommitmentPoint {
// TODO: add a variant for before our first commitment point is retrieved
/// We've advanced our commitment number and are waiting on the next commitment point.
/// Until the `get_per_commitment_point` signer method becomes async, this variant
/// will not be used.
PendingNext { transaction_number: u64, current: PublicKey },
/// Our current commitment point is ready, we've cached our next point,
/// and we are not pending a new one.
Available { transaction_number: u64, current: PublicKey, next: PublicKey },
}
impl HolderCommitmentPoint {
pub fn new<SP: Deref>(signer: &ChannelSignerType<SP>, secp_ctx: &Secp256k1<secp256k1::All>) -> Self
where SP::Target: SignerProvider
{
HolderCommitmentPoint::Available {
transaction_number: INITIAL_COMMITMENT_NUMBER,
// TODO(async_signing): remove this expect with the Uninitialized variant
current: signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER, secp_ctx)
.expect("Signer must be able to provide initial commitment point"),
// TODO(async_signing): remove this expect with the Uninitialized variant
next: signer.as_ref().get_per_commitment_point(INITIAL_COMMITMENT_NUMBER - 1, secp_ctx)
.expect("Signer must be able to provide second commitment point"),
}
}
pub fn is_available(&self) -> bool {
if let HolderCommitmentPoint::Available { .. } = self { true } else { false }
}
pub fn transaction_number(&self) -> u64 {
match self {
HolderCommitmentPoint::PendingNext { transaction_number, .. } => *transaction_number,
HolderCommitmentPoint::Available { transaction_number, .. } => *transaction_number,
}
}
pub fn current_point(&self) -> PublicKey {
match self {
HolderCommitmentPoint::PendingNext { current, .. } => *current,
HolderCommitmentPoint::Available { current, .. } => *current,
}
}
pub fn next_point(&self) -> Option<PublicKey> {