@@ -700,6 +700,11 @@ pub(crate) struct ChannelMonitorImpl<Signer: Sign> {
700
700
// remote monitor out-of-order with regards to the block view.
701
701
holder_tx_signed : bool ,
702
702
703
+ // If a spend of the funding output is seen, we set this to true and reject any further
704
+ // updates. This prevents any further changes in the offchain state no matter the order
705
+ // of block connection between ChannelMonitors and the ChannelManager.
706
+ funding_spend_seen : bool ,
707
+
703
708
funding_spend_confirmed : Option < Txid > ,
704
709
/// The set of HTLCs which have been either claimed or failed on chain and have reached
705
710
/// the requisite confirmations on the claim/fail transaction (either ANTI_REORG_DELAY or the
@@ -765,6 +770,7 @@ impl<Signer: Sign> PartialEq for ChannelMonitorImpl<Signer> {
765
770
self . outputs_to_watch != other. outputs_to_watch ||
766
771
self . lockdown_from_offchain != other. lockdown_from_offchain ||
767
772
self . holder_tx_signed != other. holder_tx_signed ||
773
+ self . funding_spend_seen != other. funding_spend_seen ||
768
774
self . funding_spend_confirmed != other. funding_spend_confirmed ||
769
775
self . htlcs_resolved_on_chain != other. htlcs_resolved_on_chain
770
776
{
@@ -940,6 +946,7 @@ impl<Signer: Sign> Writeable for ChannelMonitorImpl<Signer> {
940
946
( 1 , self . funding_spend_confirmed, option) ,
941
947
( 3 , self . htlcs_resolved_on_chain, vec_type) ,
942
948
( 5 , self . pending_monitor_events, vec_type) ,
949
+ ( 7 , self . funding_spend_seen, required) ,
943
950
} ) ;
944
951
945
952
Ok ( ( ) )
@@ -1038,6 +1045,7 @@ impl<Signer: Sign> ChannelMonitor<Signer> {
1038
1045
1039
1046
lockdown_from_offchain : false ,
1040
1047
holder_tx_signed : false ,
1048
+ funding_spend_seen : false ,
1041
1049
funding_spend_confirmed : None ,
1042
1050
htlcs_resolved_on_chain : Vec :: new ( ) ,
1043
1051
@@ -1843,6 +1851,10 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
1843
1851
}
1844
1852
}
1845
1853
self . latest_update_id = updates. update_id ;
1854
+
1855
+ if ret. is_ok ( ) && self . funding_spend_seen {
1856
+ ret = Err ( MonitorUpdateError ( "Counterparty attempted to update commitment after funding was spent" ) ) ;
1857
+ }
1846
1858
ret
1847
1859
}
1848
1860
@@ -2271,6 +2283,7 @@ impl<Signer: Sign> ChannelMonitorImpl<Signer> {
2271
2283
if prevout. txid == self . funding_info . 0 . txid && prevout. vout == self . funding_info . 0 . index as u32 {
2272
2284
let mut balance_spendable_csv = None ;
2273
2285
log_info ! ( logger, "Channel closed by funding output spend in txid {}." , log_bytes!( tx. txid( ) ) ) ;
2286
+ self . funding_spend_seen = true ;
2274
2287
if ( tx. input [ 0 ] . sequence >> 8 * 3 ) as u8 == 0x80 && ( tx. lock_time >> 8 * 3 ) as u8 == 0x20 {
2275
2288
let ( mut new_outpoints, new_outputs) = self . check_spend_counterparty_transaction ( & tx, height, & logger) ;
2276
2289
if !new_outputs. 1 . is_empty ( ) {
@@ -3120,10 +3133,12 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3120
3133
3121
3134
let mut funding_spend_confirmed = None ;
3122
3135
let mut htlcs_resolved_on_chain = Some ( Vec :: new ( ) ) ;
3136
+ let mut funding_spend_seen = Some ( false ) ;
3123
3137
read_tlv_fields ! ( reader, {
3124
3138
( 1 , funding_spend_confirmed, option) ,
3125
3139
( 3 , htlcs_resolved_on_chain, vec_type) ,
3126
3140
( 5 , pending_monitor_events, vec_type) ,
3141
+ ( 7 , funding_spend_seen, option) ,
3127
3142
} ) ;
3128
3143
3129
3144
let mut secp_ctx = Secp256k1 :: new ( ) ;
@@ -3173,6 +3188,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3173
3188
3174
3189
lockdown_from_offchain,
3175
3190
holder_tx_signed,
3191
+ funding_spend_seen : funding_spend_seen. unwrap ( ) ,
3176
3192
funding_spend_confirmed,
3177
3193
htlcs_resolved_on_chain : htlcs_resolved_on_chain. unwrap ( ) ,
3178
3194
@@ -3186,6 +3202,7 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
3186
3202
3187
3203
#[ cfg( test) ]
3188
3204
mod tests {
3205
+ use bitcoin:: blockdata:: block:: BlockHeader ;
3189
3206
use bitcoin:: blockdata:: script:: { Script , Builder } ;
3190
3207
use bitcoin:: blockdata:: opcodes;
3191
3208
use bitcoin:: blockdata:: transaction:: { Transaction , TxIn , TxOut , SigHashType } ;
@@ -3194,24 +3211,125 @@ mod tests {
3194
3211
use bitcoin:: hashes:: Hash ;
3195
3212
use bitcoin:: hashes:: sha256:: Hash as Sha256 ;
3196
3213
use bitcoin:: hashes:: hex:: FromHex ;
3197
- use bitcoin:: hash_types:: Txid ;
3214
+ use bitcoin:: hash_types:: { BlockHash , Txid } ;
3198
3215
use bitcoin:: network:: constants:: Network ;
3216
+ use bitcoin:: secp256k1:: key:: { SecretKey , PublicKey } ;
3217
+ use bitcoin:: secp256k1:: Secp256k1 ;
3218
+
3199
3219
use hex;
3200
- use chain:: BestBlock ;
3220
+
3221
+ use super :: ChannelMonitorUpdateStep ;
3222
+ use :: { check_added_monitors, check_closed_broadcast, check_closed_event, check_spends, get_local_commitment_txn, get_monitor, get_route_and_payment_hash, unwrap_send_err} ;
3223
+ use chain:: { BestBlock , Confirm } ;
3201
3224
use chain:: channelmonitor:: ChannelMonitor ;
3202
3225
use chain:: package:: { WEIGHT_OFFERED_HTLC , WEIGHT_RECEIVED_HTLC , WEIGHT_REVOKED_OFFERED_HTLC , WEIGHT_REVOKED_RECEIVED_HTLC , WEIGHT_REVOKED_OUTPUT } ;
3203
3226
use chain:: transaction:: OutPoint ;
3227
+ use chain:: keysinterface:: InMemorySigner ;
3204
3228
use ln:: { PaymentPreimage , PaymentHash } ;
3205
3229
use ln:: chan_utils;
3206
3230
use ln:: chan_utils:: { HTLCOutputInCommitment , ChannelPublicKeys , ChannelTransactionParameters , HolderCommitmentTransaction , CounterpartyChannelTransactionParameters } ;
3231
+ use ln:: channelmanager:: PaymentSendFailure ;
3232
+ use ln:: features:: InitFeatures ;
3233
+ use ln:: functional_test_utils:: * ;
3207
3234
use ln:: script:: ShutdownScript ;
3235
+ use util:: errors:: APIError ;
3236
+ use util:: events:: { ClosureReason , MessageSendEventsProvider } ;
3208
3237
use util:: test_utils:: { TestLogger , TestBroadcaster , TestFeeEstimator } ;
3209
- use bitcoin:: secp256k1:: key:: { SecretKey , PublicKey } ;
3210
- use bitcoin:: secp256k1:: Secp256k1 ;
3238
+ use util:: ser:: { ReadableArgs , Writeable } ;
3211
3239
use sync:: { Arc , Mutex } ;
3212
- use chain :: keysinterface :: InMemorySigner ;
3240
+ use io ;
3213
3241
use prelude:: * ;
3214
3242
3243
+ fn do_test_funding_spend_refuses_updates ( use_local_txn : bool ) {
3244
+ // Previously, monitor updates were allowed freely even after a funding-spend transaction
3245
+ // confirmed. This would allow a race condition where we could receive a payment (including
3246
+ // the counterparty revoking their broadcasted state!) and accept it without recourse as
3247
+ // long as the ChannelMonitor receives the block first, the full commitment update dance
3248
+ // occurs after the block is connected, and before the ChannelManager receives the block.
3249
+ // Obviously this is an incredibly contrived race given the counterparty would be risking
3250
+ // their full channel balance for it, but its worth fixing nonetheless as it makes the
3251
+ // potential ChannelMonitor states simpler to reason about.
3252
+ //
3253
+ // This test checks said behavior, as well as ensuring a ChannelMonitorUpdate with multiple
3254
+ // updates is handled correctly in such conditions.
3255
+ let chanmon_cfgs = create_chanmon_cfgs ( 3 ) ;
3256
+ let node_cfgs = create_node_cfgs ( 3 , & chanmon_cfgs) ;
3257
+ let node_chanmgrs = create_node_chanmgrs ( 3 , & node_cfgs, & [ None , None , None ] ) ;
3258
+ let nodes = create_network ( 3 , & node_cfgs, & node_chanmgrs) ;
3259
+ let channel = create_announced_chan_between_nodes (
3260
+ & nodes, 0 , 1 , InitFeatures :: known ( ) , InitFeatures :: known ( ) ) ;
3261
+ create_announced_chan_between_nodes (
3262
+ & nodes, 1 , 2 , InitFeatures :: known ( ) , InitFeatures :: known ( ) ) ;
3263
+
3264
+ // Rebalance somewhat
3265
+ send_payment ( & nodes[ 0 ] , & [ & nodes[ 1 ] ] , 10_000_000 ) ;
3266
+
3267
+ // First route two payments for testing at the end
3268
+ let payment_preimage_1 = route_payment ( & nodes[ 0 ] , & [ & nodes[ 1 ] , & nodes[ 2 ] ] , 1_000_000 ) . 0 ;
3269
+ let payment_preimage_2 = route_payment ( & nodes[ 0 ] , & [ & nodes[ 1 ] , & nodes[ 2 ] ] , 1_000_000 ) . 0 ;
3270
+
3271
+ let local_txn = get_local_commitment_txn ! ( nodes[ 1 ] , channel. 2 ) ;
3272
+ assert_eq ! ( local_txn. len( ) , 1 ) ;
3273
+ let remote_txn = get_local_commitment_txn ! ( nodes[ 0 ] , channel. 2 ) ;
3274
+ assert_eq ! ( remote_txn. len( ) , 3 ) ; // Commitment and two HTLC-Timeouts
3275
+ check_spends ! ( remote_txn[ 1 ] , remote_txn[ 0 ] ) ;
3276
+ check_spends ! ( remote_txn[ 2 ] , remote_txn[ 0 ] ) ;
3277
+ let broadcast_tx = if use_local_txn { & local_txn[ 0 ] } else { & remote_txn[ 0 ] } ;
3278
+
3279
+ // Connect a commitment transaction, but only to the ChainMonitor/ChannelMonitor. The
3280
+ // channel is now closed, but the ChannelManager doesn't know that yet.
3281
+ let new_header = BlockHeader {
3282
+ version : 2 , time : 0 , bits : 0 , nonce : 0 ,
3283
+ prev_blockhash : nodes[ 0 ] . best_block_info ( ) . 0 ,
3284
+ merkle_root : Default :: default ( ) } ;
3285
+ let conf_height = nodes[ 0 ] . best_block_info ( ) . 1 + 1 ;
3286
+ nodes[ 1 ] . chain_monitor . chain_monitor . transactions_confirmed ( & new_header,
3287
+ & [ ( 0 , broadcast_tx) ] , conf_height) ;
3288
+
3289
+ let ( _, pre_update_monitor) = <( BlockHash , ChannelMonitor < InMemorySigner > ) >:: read (
3290
+ & mut io:: Cursor :: new ( & get_monitor ! ( nodes[ 1 ] , channel. 2 ) . encode ( ) ) ,
3291
+ & nodes[ 1 ] . keys_manager . backing ) . unwrap ( ) ;
3292
+
3293
+ // If the ChannelManager tries to update the channel, however, the ChainMonitor will pass
3294
+ // the update through to the ChannelMonitor which will refuse it (as the channel is closed).
3295
+ let ( route, payment_hash, _, payment_secret) = get_route_and_payment_hash ! ( nodes[ 1 ] , nodes[ 0 ] , 100_000 ) ;
3296
+ unwrap_send_err ! ( nodes[ 1 ] . node. send_payment( & route, payment_hash, & Some ( payment_secret) ) ,
3297
+ true , APIError :: ChannelUnavailable { ref err } ,
3298
+ assert!( err. contains( "ChannelMonitor storage failure" ) ) ) ;
3299
+ check_added_monitors ! ( nodes[ 1 ] , 2 ) ; // After the failure we generate a close-channel monitor update
3300
+ check_closed_broadcast ! ( nodes[ 1 ] , true ) ;
3301
+ check_closed_event ! ( nodes[ 1 ] , 1 , ClosureReason :: ProcessingError { err: "ChannelMonitor storage failure" . to_string( ) } ) ;
3302
+
3303
+ let monitor_updates = nodes[ 1 ] . chain_monitor . monitor_updates . lock ( ) . unwrap ( ) ;
3304
+ let mut replay_update = monitor_updates. get ( & channel. 2 ) . unwrap ( ) . iter ( ) . rev ( ) . skip ( 1 ) . next ( ) . unwrap ( ) . clone ( ) ;
3305
+ assert_eq ! ( replay_update. updates. len( ) , 1 ) ;
3306
+ if let ChannelMonitorUpdateStep :: LatestCounterpartyCommitmentTXInfo { .. } = replay_update. updates [ 0 ] {
3307
+ } else { panic ! ( ) ; }
3308
+ replay_update. updates . push ( ChannelMonitorUpdateStep :: PaymentPreimage { payment_preimage : payment_preimage_1 } ) ;
3309
+ replay_update. updates . push ( ChannelMonitorUpdateStep :: PaymentPreimage { payment_preimage : payment_preimage_2 } ) ;
3310
+
3311
+ let broadcaster = TestBroadcaster :: new ( Arc :: clone ( & nodes[ 1 ] . blocks ) ) ;
3312
+ assert ! (
3313
+ pre_update_monitor. update_monitor( & replay_update, &&broadcaster, &&chanmon_cfgs[ 1 ] . fee_estimator, & nodes[ 1 ] . logger)
3314
+ . is_err( ) ) ;
3315
+ // Even though we error'd on the first update, we should still have generated an HTLC claim
3316
+ // transaction
3317
+ let txn_broadcasted = broadcaster. txn_broadcasted . lock ( ) . unwrap ( ) . split_off ( 0 ) ;
3318
+ assert ! ( txn_broadcasted. len( ) >= 2 ) ;
3319
+ let htlc_txn = txn_broadcasted. iter ( ) . filter ( |tx| {
3320
+ assert_eq ! ( tx. input. len( ) , 1 ) ;
3321
+ tx. input [ 0 ] . previous_output . txid == broadcast_tx. txid ( )
3322
+ } ) . collect :: < Vec < _ > > ( ) ;
3323
+ assert_eq ! ( htlc_txn. len( ) , 2 ) ;
3324
+ check_spends ! ( htlc_txn[ 0 ] , broadcast_tx) ;
3325
+ check_spends ! ( htlc_txn[ 1 ] , broadcast_tx) ;
3326
+ }
3327
+ #[ test]
3328
+ fn test_funding_spend_refuses_updates ( ) {
3329
+ do_test_funding_spend_refuses_updates ( true ) ;
3330
+ do_test_funding_spend_refuses_updates ( false ) ;
3331
+ }
3332
+
3215
3333
#[ test]
3216
3334
fn test_prune_preimages ( ) {
3217
3335
let secp_ctx = Secp256k1 :: new ( ) ;
0 commit comments