@@ -33,7 +33,7 @@ use ln::chan_utils;
33
33
use chain:: chaininterface:: { FeeEstimator , ConfirmationTarget } ;
34
34
use chain:: transaction:: OutPoint ;
35
35
use chain:: keysinterface:: { ChannelKeys , KeysInterface } ;
36
- use util:: transaction_utils;
36
+ use util:: { byte_utils , transaction_utils} ;
37
37
use util:: ser:: { Readable , Writeable , Writer } ;
38
38
use util:: logger:: Logger ;
39
39
use util:: errors:: APIError ;
@@ -43,6 +43,7 @@ use std;
43
43
use std:: default:: Default ;
44
44
use std:: { cmp, mem, fmt} ;
45
45
use std:: ops:: Deref ;
46
+ use std:: collections:: HashMap ;
46
47
use bitcoin:: hashes:: hex:: ToHex ;
47
48
48
49
#[ cfg( test) ]
@@ -104,16 +105,18 @@ enum InboundHTLCState {
104
105
AwaitingAnnouncedRemoteRevoke ( PendingHTLCStatus ) ,
105
106
Committed ,
106
107
/// Removed by us and a new commitment_signed was sent (if we were AwaitingRemoteRevoke when we
107
- /// created it we would have put it in the holding cell instead). When they next revoke_and_ack
108
- /// we'll drop it.
108
+ /// created it we would have put it in the holding cell instead).
109
109
/// Note that we have to keep an eye on the HTLC until we've received a broadcastable
110
110
/// commitment transaction without it as otherwise we'll have to force-close the channel to
111
111
/// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim
112
- /// anyway). That said, ChannelMonitor does this for us (see
113
- /// ChannelMonitor::would_broadcast_at_height) so we actually remove the HTLC from our own
114
- /// local state before then, once we're sure that the next commitment_signed and
115
- /// ChannelMonitor::provide_latest_local_commitment_tx_info will not include this HTLC.
112
+ /// anyway).
116
113
LocalRemoved ( InboundHTLCRemovalReason ) ,
114
+ /// Removed by us and by the remote.
115
+ /// Note that we have to keep an eye on the HTLC until we've received a broadcastable
116
+ /// commitment transaction without it as otherwise we'll have to force-close the channel to
117
+ /// claim it before the timeout (obviously doesn't apply to revoked HTLCs that we can't claim
118
+ /// anyway).
119
+ RemoteRemoved ,
117
120
}
118
121
119
122
struct InboundHTLCOutput {
@@ -293,6 +296,7 @@ pub(super) struct Channel<ChanSigner: ChannelKeys> {
293
296
pending_inbound_htlcs : Vec < InboundHTLCOutput > ,
294
297
pending_outbound_htlcs : Vec < OutboundHTLCOutput > ,
295
298
holding_cell_htlc_updates : Vec < HTLCUpdateAwaitingACK > ,
299
+ payment_preimages : HashMap < PaymentHash , PaymentPreimage > ,
296
300
297
301
/// When resending CS/RAA messages on channel monitor restoration or on reconnect, we always
298
302
/// need to ensure we resend them in the order we originally generated them. Note that because
@@ -510,6 +514,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
510
514
pending_inbound_htlcs : Vec :: new ( ) ,
511
515
pending_outbound_htlcs : Vec :: new ( ) ,
512
516
holding_cell_htlc_updates : Vec :: new ( ) ,
517
+ payment_preimages : HashMap :: new ( ) ,
513
518
pending_update_fee : None ,
514
519
holding_cell_update_fee : None ,
515
520
next_local_htlc_id : 0 ,
@@ -738,6 +743,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
738
743
pending_inbound_htlcs : Vec :: new ( ) ,
739
744
pending_outbound_htlcs : Vec :: new ( ) ,
740
745
holding_cell_htlc_updates : Vec :: new ( ) ,
746
+ payment_preimages : HashMap :: new ( ) ,
741
747
pending_update_fee : None ,
742
748
holding_cell_update_fee : None ,
743
749
next_local_htlc_id : 0 ,
@@ -795,6 +801,57 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
795
801
Ok ( chan)
796
802
}
797
803
804
+ pub ( super ) fn monitor_would_broadcast_at_height < L : Deref > ( & self , height : u32 , logger : & L ) -> bool where L :: Target : Logger {
805
+ macro_rules! get_htlc_output {
806
+ ( $htlc: expr, $offered: expr) => {
807
+ HTLCOutputInCommitment {
808
+ offered: $offered,
809
+ amount_msat: $htlc. amount_msat,
810
+ cltv_expiry: $htlc. cltv_expiry,
811
+ payment_hash: $htlc. payment_hash,
812
+ transaction_output_index: None
813
+ }
814
+ }
815
+ }
816
+ let inbound_local_outputs = self . pending_inbound_htlcs . iter ( )
817
+ . map ( |htlc| get_htlc_output ! ( htlc, false ) ) ;
818
+
819
+ let outbound_local_outputs = self . pending_outbound_htlcs . iter ( )
820
+ . filter_map ( |htlc| {
821
+ match htlc. state {
822
+ OutboundHTLCState :: AwaitingRemovedRemoteRevoke ( _) => None ,
823
+ _ => Some ( get_htlc_output ! ( htlc, true ) )
824
+ }
825
+ } ) ;
826
+ let awaiting_raa = ( self . channel_state & ChannelState :: AwaitingRemoteRevoke as u32 ) != 0 ;
827
+ let inbound_remote_outputs = self . pending_inbound_htlcs . iter ( )
828
+ . filter_map ( |htlc| {
829
+ match htlc. state {
830
+ InboundHTLCState :: LocalRemoved ( _) => {
831
+ if awaiting_raa {
832
+ Some ( get_htlc_output ! ( htlc, true ) )
833
+ } else { None }
834
+ } ,
835
+ InboundHTLCState :: AwaitingRemoteRevokeToAnnounce ( _) => None ,
836
+ InboundHTLCState :: RemoteRemoved => None ,
837
+ _ => Some ( get_htlc_output ! ( htlc, true ) )
838
+ }
839
+ } ) ;
840
+ let outbound_remote_outputs = self . pending_outbound_htlcs . iter ( )
841
+ . filter_map ( |htlc| {
842
+ match htlc. state {
843
+ OutboundHTLCState :: AwaitingRemovedRemoteRevoke ( _) => {
844
+ if awaiting_raa {
845
+ Some ( get_htlc_output ! ( htlc, false ) )
846
+ } else { None }
847
+ } ,
848
+ _ => Some ( get_htlc_output ! ( htlc, false ) )
849
+ }
850
+ } ) ;
851
+
852
+ ChannelMonitor :: < ChanSigner > :: would_broadcast_at_height_given_htlcs ( inbound_local_outputs. chain ( outbound_local_outputs) , inbound_remote_outputs. chain ( outbound_remote_outputs) , height, & self . payment_preimages , logger)
853
+ }
854
+
798
855
// Utilities to build transactions:
799
856
800
857
fn get_commitment_transaction_number_obscure_factor ( & self ) -> u64 {
@@ -909,6 +966,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
909
966
InboundHTLCState :: AwaitingAnnouncedRemoteRevoke ( _) => ( true , "AwaitingAnnouncedRemoteRevoke" ) ,
910
967
InboundHTLCState :: Committed => ( true , "Committed" ) ,
911
968
InboundHTLCState :: LocalRemoved ( _) => ( !generated_by_local, "LocalRemoved" ) ,
969
+ InboundHTLCState :: RemoteRemoved => ( false , "RemoteRemoved" ) ,
912
970
} ;
913
971
914
972
if include {
@@ -1216,6 +1274,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
1216
1274
// We have to put the payment_preimage in the channel_monitor right away here to ensure we
1217
1275
// can claim it even if the channel hits the chain before we see their next commitment.
1218
1276
self . latest_monitor_update_id += 1 ;
1277
+ self . payment_preimages . insert ( payment_hash_calc, payment_preimage_arg. clone ( ) ) ;
1219
1278
let monitor_update = ChannelMonitorUpdate {
1220
1279
update_id : self . latest_monitor_update_id ,
1221
1280
updates : vec ! [ ChannelMonitorUpdateStep :: PaymentPreimage {
@@ -2011,6 +2070,23 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
2011
2070
return Err ( ( None , ChannelError :: Close ( format ! ( "Got wrong number of HTLC signatures ({}) from remote. It must be {}" , msg. htlc_signatures. len( ) , local_commitment_tx. 1 ) ) ) ) ;
2012
2071
}
2013
2072
2073
+ {
2074
+
2075
+ let pending_inbound_htlcs: & mut Vec < _ > = & mut self . pending_inbound_htlcs ;
2076
+ let payment_preimages: & mut HashMap < _ , _ > = & mut self . payment_preimages ;
2077
+ // A RemoteRemoved HTLC need to be monitored for expiration until we receive a
2078
+ // broadcastable commitment tx without said HTLC. Now that we've confirmed that
2079
+ // this commitment signed message provides said commitment tx, we can drop the
2080
+ // RemoteRemoved HTLCs we were previously watching for.
2081
+ pending_inbound_htlcs. retain ( |htlc| {
2082
+ log_trace ! ( logger, "Removing inbound RemovedRemoved {}" , log_bytes!( htlc. payment_hash. 0 ) ) ;
2083
+ if let & InboundHTLCState :: RemoteRemoved = & htlc. state {
2084
+ payment_preimages. remove ( & htlc. payment_hash ) ;
2085
+ false
2086
+ } else { true }
2087
+ } ) ;
2088
+ }
2089
+
2014
2090
// TODO: Merge these two, sadly they are currently both required to be passed separately to
2015
2091
// ChannelMonitor:
2016
2092
let mut htlcs_without_source = Vec :: with_capacity ( local_commitment_tx. 2 . len ( ) ) ;
@@ -2303,30 +2379,20 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
2303
2379
// Take references explicitly so that we can hold multiple references to self.
2304
2380
let pending_inbound_htlcs: & mut Vec < _ > = & mut self . pending_inbound_htlcs ;
2305
2381
let pending_outbound_htlcs: & mut Vec < _ > = & mut self . pending_outbound_htlcs ;
2306
-
2307
- // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug)
2308
- pending_inbound_htlcs . retain ( |htlc| {
2382
+ let payment_preimages : & mut HashMap < _ , _ > = & mut self . payment_preimages ;
2383
+ for htlc in pending_inbound_htlcs . iter_mut ( ) {
2384
+ let mut is_local_removed = false ;
2309
2385
if let & InboundHTLCState :: LocalRemoved ( ref reason) = & htlc. state {
2310
- log_trace ! ( logger, " ...removing inbound LocalRemoved {}" , log_bytes!( htlc. payment_hash. 0 ) ) ;
2311
2386
if let & InboundHTLCRemovalReason :: Fulfill ( _) = reason {
2312
2387
value_to_self_msat_diff += htlc. amount_msat as i64 ;
2313
2388
}
2314
- false
2315
- } else { true }
2316
- } ) ;
2317
- pending_outbound_htlcs. retain ( |htlc| {
2318
- if let & OutboundHTLCState :: AwaitingRemovedRemoteRevoke ( ref fail_reason) = & htlc. state {
2319
- log_trace ! ( logger, " ...removing outbound AwaitingRemovedRemoteRevoke {}" , log_bytes!( htlc. payment_hash. 0 ) ) ;
2320
- if let Some ( reason) = fail_reason. clone ( ) { // We really want take() here, but, again, non-mut ref :(
2321
- revoked_htlcs. push ( ( htlc. source . clone ( ) , htlc. payment_hash , reason) ) ;
2322
- } else {
2323
- // They fulfilled, so we sent them money
2324
- value_to_self_msat_diff -= htlc. amount_msat as i64 ;
2325
- }
2326
- false
2327
- } else { true }
2328
- } ) ;
2329
- for htlc in pending_inbound_htlcs. iter_mut ( ) {
2389
+ is_local_removed = true ;
2390
+ }
2391
+ if is_local_removed {
2392
+ let mut state = InboundHTLCState :: RemoteRemoved ;
2393
+ mem:: swap ( & mut state, & mut htlc. state ) ;
2394
+ continue
2395
+ }
2330
2396
let swap = if let & InboundHTLCState :: AwaitingRemoteRevokeToAnnounce ( _) = & htlc. state {
2331
2397
log_trace ! ( logger, " ...promoting inbound AwaitingRemoteRevokeToAnnounce {} to Committed" , log_bytes!( htlc. payment_hash. 0 ) ) ;
2332
2398
true
@@ -2364,6 +2430,20 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
2364
2430
}
2365
2431
}
2366
2432
}
2433
+ // We really shouldnt have two passes here, but retain gives a non-mutable ref (Rust bug)
2434
+ pending_outbound_htlcs. retain ( |htlc| {
2435
+ if let & OutboundHTLCState :: AwaitingRemovedRemoteRevoke ( ref fail_reason) = & htlc. state {
2436
+ log_trace ! ( logger, " ...removing outbound AwaitingRemovedRemoteRevoke {}" , log_bytes!( htlc. payment_hash. 0 ) ) ;
2437
+ if let Some ( reason) = fail_reason. clone ( ) { // We really want take() here, but, again, non-mut ref :(
2438
+ revoked_htlcs. push ( ( htlc. source . clone ( ) , htlc. payment_hash , reason) ) ;
2439
+ } else {
2440
+ // They fulfilled, so we sent them money
2441
+ value_to_self_msat_diff -= htlc. amount_msat as i64 ;
2442
+ }
2443
+ payment_preimages. remove ( & htlc. payment_hash ) ;
2444
+ false
2445
+ } else { true }
2446
+ } ) ;
2367
2447
for htlc in pending_outbound_htlcs. iter_mut ( ) {
2368
2448
if let OutboundHTLCState :: LocalAnnounced ( _) = htlc. state {
2369
2449
log_trace ! ( logger, " ...promoting outbound LocalAnnounced {} to Committed" , log_bytes!( htlc. payment_hash. 0 ) ) ;
@@ -2540,6 +2620,7 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
2540
2620
// the commitment_signed we can re-transmit the update then.
2541
2621
true
2542
2622
} ,
2623
+ InboundHTLCState :: RemoteRemoved => true ,
2543
2624
}
2544
2625
} ) ;
2545
2626
self . next_remote_htlc_id -= inbound_drop_count;
@@ -3115,14 +3196,6 @@ impl<ChanSigner: ChannelKeys> Channel<ChanSigner> {
3115
3196
self . user_id
3116
3197
}
3117
3198
3118
- /// May only be called after funding has been initiated (ie is_funding_initiated() is true)
3119
- pub fn channel_monitor ( & mut self ) -> & mut ChannelMonitor < ChanSigner > {
3120
- if self . channel_state < ChannelState :: FundingSent as u32 {
3121
- panic ! ( "Can't get a channel monitor until funding has been created" ) ;
3122
- }
3123
- self . channel_monitor . as_mut ( ) . unwrap ( )
3124
- }
3125
-
3126
3199
/// Guaranteed to be Some after both FundingLocked messages have been exchanged (and, thus,
3127
3200
/// is_usable() returns true).
3128
3201
/// Allowed in any state (including after shutdown)
@@ -4118,6 +4191,9 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
4118
4191
4u8 . write ( writer) ?;
4119
4192
removal_reason. write ( writer) ?;
4120
4193
} ,
4194
+ & InboundHTLCState :: RemoteRemoved => {
4195
+ 5u8 . write ( writer) ?;
4196
+ }
4121
4197
}
4122
4198
}
4123
4199
@@ -4151,6 +4227,11 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
4151
4227
}
4152
4228
}
4153
4229
4230
+ writer. write_all ( & byte_utils:: be64_to_array ( self . payment_preimages . len ( ) as u64 ) ) ?;
4231
+ for payment_preimage in self . payment_preimages . values ( ) {
4232
+ writer. write_all ( & payment_preimage. 0 [ ..] ) ?;
4233
+ }
4234
+
4154
4235
( self . holding_cell_htlc_updates . len ( ) as u64 ) . write ( writer) ?;
4155
4236
for update in self . holding_cell_htlc_updates . iter ( ) {
4156
4237
match update {
@@ -4248,6 +4329,8 @@ impl<ChanSigner: ChannelKeys + Writeable> Writeable for Channel<ChanSigner> {
4248
4329
}
4249
4330
}
4250
4331
4332
+ const MAX_ALLOC_SIZE : usize = 64 * 1024 ;
4333
+
4251
4334
impl < ChanSigner : ChannelKeys + Readable > Readable for Channel < ChanSigner > {
4252
4335
fn read < R : :: std:: io:: Read > ( reader : & mut R ) -> Result < Self , DecodeError > {
4253
4336
let _ver: u8 = Readable :: read ( reader) ?;
@@ -4287,6 +4370,7 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
4287
4370
2 => InboundHTLCState :: AwaitingAnnouncedRemoteRevoke ( Readable :: read ( reader) ?) ,
4288
4371
3 => InboundHTLCState :: Committed ,
4289
4372
4 => InboundHTLCState :: LocalRemoved ( Readable :: read ( reader) ?) ,
4373
+ 5 => InboundHTLCState :: RemoteRemoved ,
4290
4374
_ => return Err ( DecodeError :: InvalidValue ) ,
4291
4375
} ,
4292
4376
} ) ;
@@ -4312,6 +4396,16 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
4312
4396
} ) ;
4313
4397
}
4314
4398
4399
+ let payment_preimages_len: u64 = Readable :: read ( reader) ?;
4400
+ let mut payment_preimages = HashMap :: with_capacity ( cmp:: min ( payment_preimages_len as usize , MAX_ALLOC_SIZE / 32 ) ) ;
4401
+ for _ in 0 ..payment_preimages_len {
4402
+ let preimage: PaymentPreimage = Readable :: read ( reader) ?;
4403
+ let hash = PaymentHash ( Sha256 :: hash ( & preimage. 0 [ ..] ) . into_inner ( ) ) ;
4404
+ if let Some ( _) = payment_preimages. insert ( hash, preimage) {
4405
+ return Err ( DecodeError :: InvalidValue ) ;
4406
+ }
4407
+ }
4408
+
4315
4409
let holding_cell_htlc_update_count: u64 = Readable :: read ( reader) ?;
4316
4410
let mut holding_cell_htlc_updates = Vec :: with_capacity ( cmp:: min ( holding_cell_htlc_update_count as usize , OUR_MAX_HTLCS as usize * 2 ) ) ;
4317
4411
for _ in 0 ..holding_cell_htlc_update_count {
@@ -4428,6 +4522,7 @@ impl<ChanSigner: ChannelKeys + Readable> Readable for Channel<ChanSigner> {
4428
4522
pending_inbound_htlcs,
4429
4523
pending_outbound_htlcs,
4430
4524
holding_cell_htlc_updates,
4525
+ payment_preimages,
4431
4526
4432
4527
resend_order,
4433
4528
0 commit comments