Skip to content

Commit c9d03d4

Browse files
committed
store channel in monitor
1 parent dcad93c commit c9d03d4

16 files changed

+280
-172
lines changed

lightning/Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ _externalize_tests = ["inventory", "_test_utils"]
2222
# Allow signing of local transactions that may have been revoked or will be revoked, for functional testing (e.g. justice tx handling).
2323
# This is unsafe to use in production because it may result in the counterparty publishing taking our funds.
2424
unsafe_revoked_tx_signing = []
25+
safe_channels = []
2526

2627
std = []
2728

lightning/src/chain/channelmonitor.rs

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -111,6 +111,9 @@ pub struct ChannelMonitorUpdate {
111111
/// Will be `None` for `ChannelMonitorUpdate`s constructed on LDK versions prior to 0.0.121 and
112112
/// always `Some` otherwise.
113113
pub channel_id: Option<ChannelId>,
114+
115+
/// The encoded channel data associated with this ChannelMonitor, if any.
116+
pub encoded_channel: Option<Vec<u8>>,
114117
}
115118

116119
impl ChannelMonitorUpdate {
@@ -156,6 +159,13 @@ impl Writeable for ChannelMonitorUpdate {
156159
for update_step in self.updates.iter() {
157160
update_step.write(w)?;
158161
}
162+
#[cfg(feature = "safe_channels")]
163+
write_tlv_fields!(w, {
164+
// 1 was previously used to store `counterparty_node_id`
165+
(3, self.channel_id, option),
166+
(5, self.encoded_channel, option)
167+
});
168+
#[cfg(not(feature = "safe_channels"))]
159169
write_tlv_fields!(w, {
160170
// 1 was previously used to store `counterparty_node_id`
161171
(3, self.channel_id, option),
@@ -176,11 +186,13 @@ impl Readable for ChannelMonitorUpdate {
176186
}
177187
}
178188
let mut channel_id = None;
189+
let mut encoded_channel = None;
179190
read_tlv_fields!(r, {
180191
// 1 was previously used to store `counterparty_node_id`
181192
(3, channel_id, option),
193+
(5, encoded_channel, option)
182194
});
183-
Ok(Self { update_id, updates, channel_id })
195+
Ok(Self { update_id, updates, channel_id, encoded_channel })
184196
}
185197
}
186198

@@ -1402,6 +1414,8 @@ pub(crate) struct ChannelMonitorImpl<Signer: EcdsaChannelSigner> {
14021414
/// make deciding whether to do so simple, here we track whether this monitor was last written
14031415
/// prior to 0.1.
14041416
written_by_0_1_or_later: bool,
1417+
1418+
encoded_channel: Option<Vec<u8>>,
14051419
}
14061420

14071421
// Returns a `&FundingScope` for the one we are currently observing/handling commitment transactions
@@ -1733,6 +1747,32 @@ pub(crate) fn write_chanmon_internal<Signer: EcdsaChannelSigner, W: Writer>(
17331747
_ => channel_monitor.pending_monitor_events.clone(),
17341748
};
17351749

1750+
#[cfg(feature = "safe_channels")]
1751+
write_tlv_fields!(writer, {
1752+
(1, channel_monitor.funding_spend_confirmed, option),
1753+
(3, channel_monitor.htlcs_resolved_on_chain, required_vec),
1754+
(5, pending_monitor_events, required_vec),
1755+
(7, channel_monitor.funding_spend_seen, required),
1756+
(9, channel_monitor.counterparty_node_id, required),
1757+
(11, channel_monitor.confirmed_commitment_tx_counterparty_output, option),
1758+
(13, channel_monitor.spendable_txids_confirmed, required_vec),
1759+
(15, channel_monitor.counterparty_fulfilled_htlcs, required),
1760+
(17, channel_monitor.initial_counterparty_commitment_info, option),
1761+
(19, channel_monitor.channel_id, required),
1762+
(21, channel_monitor.balances_empty_height, option),
1763+
(23, channel_monitor.holder_pays_commitment_tx_fee, option),
1764+
(25, channel_monitor.payment_preimages, required),
1765+
(27, channel_monitor.first_negotiated_funding_txo, required),
1766+
(29, channel_monitor.initial_counterparty_commitment_tx, option),
1767+
(31, channel_monitor.funding.channel_parameters, required),
1768+
(32, channel_monitor.pending_funding, optional_vec),
1769+
(33, channel_monitor.htlcs_resolved_to_user, required),
1770+
(34, channel_monitor.alternative_funding_confirmed, option),
1771+
(35, channel_monitor.is_manual_broadcast, required),
1772+
(37, channel_monitor.funding_seen_onchain, required),
1773+
(39, channel_monitor.encoded_channel, option),
1774+
});
1775+
#[cfg(not(feature = "safe_channels"))]
17361776
write_tlv_fields!(writer, {
17371777
(1, channel_monitor.funding_spend_confirmed, option),
17381778
(3, channel_monitor.htlcs_resolved_on_chain, required_vec),
@@ -1994,6 +2034,7 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
19942034
alternative_funding_confirmed: None,
19952035

19962036
written_by_0_1_or_later: true,
2037+
encoded_channel: None,
19972038
})
19982039
}
19992040

@@ -2114,6 +2155,16 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
21142155
inner.update_monitor(updates, broadcaster, fee_estimator, &logger)
21152156
}
21162157

2158+
/// Gets the encoded channel data, if any, associated with this ChannelMonitor.
2159+
pub fn get_encoded_channel(&self) -> Option<Vec<u8>> {
2160+
self.inner.lock().unwrap().encoded_channel.clone()
2161+
}
2162+
2163+
/// Updates the encoded channel data associated with this ChannelMonitor.
2164+
pub fn update_encoded_channel(&self, encoded: Vec<u8>) {
2165+
self.inner.lock().unwrap().encoded_channel = Some(encoded);
2166+
}
2167+
21172168
/// Gets the update_id from the latest ChannelMonitorUpdate which was applied to this
21182169
/// ChannelMonitor.
21192170
///
@@ -4405,9 +4456,18 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitorImpl<Signer> {
44054456
}
44064457
}
44074458

4408-
if ret.is_ok() && self.no_further_updates_allowed() && is_pre_close_update {
4409-
log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
4410-
Err(())
4459+
if ret.is_ok() {
4460+
if self.no_further_updates_allowed() && is_pre_close_update {
4461+
log_error!(logger, "Refusing Channel Monitor Update as counterparty attempted to update commitment after funding was spent");
4462+
Err(())
4463+
} else {
4464+
// Assume that if the updates contains no encoded channel, that the channel remained unchanged. We
4465+
// therefore do not update the monitor.
4466+
if let Some(encoded_channel) = updates.encoded_channel.as_ref() {
4467+
self.encoded_channel = Some(encoded_channel.clone());
4468+
}
4469+
Ok(())
4470+
}
44114471
} else { ret }
44124472
}
44134473

@@ -6645,6 +6705,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
66456705
let mut alternative_funding_confirmed = None;
66466706
let mut is_manual_broadcast = RequiredWrapper(None);
66476707
let mut funding_seen_onchain = RequiredWrapper(None);
6708+
let mut encoded_channel = None;
66486709
read_tlv_fields!(reader, {
66496710
(1, funding_spend_confirmed, option),
66506711
(3, htlcs_resolved_on_chain, optional_vec),
@@ -6667,6 +6728,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
66676728
(34, alternative_funding_confirmed, option),
66686729
(35, is_manual_broadcast, (default_value, false)),
66696730
(37, funding_seen_onchain, (default_value, true)),
6731+
(39, encoded_channel, option),
66706732
});
66716733
// Note that `payment_preimages_with_info` was added (and is always written) in LDK 0.1, so
66726734
// we can use it to determine if this monitor was last written by LDK 0.1 or later.
@@ -6844,6 +6906,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
68446906
alternative_funding_confirmed,
68456907

68466908
written_by_0_1_or_later,
6909+
encoded_channel,
68476910
});
68486911

68496912
if counterparty_node_id.is_none() {

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2839,6 +2839,8 @@ fn do_channel_holding_cell_serialize(disconnect: bool, reload_a: bool) {
28392839
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_1);
28402840
claim_payment(&nodes[0], &[&nodes[1]], payment_preimage_2);
28412841
}
2842+
2843+
#[cfg(not(feature = "safe_channels"))]
28422844
#[test]
28432845
fn channel_holding_cell_serialize() {
28442846
do_channel_holding_cell_serialize(true, true);
@@ -3320,6 +3322,7 @@ fn do_test_outbound_reload_without_init_mon(use_0conf: bool) {
33203322
assert!(nodes[0].node.list_channels().is_empty());
33213323
}
33223324

3325+
#[cfg(not(feature = "safe_channels"))]
33233326
#[test]
33243327
fn test_outbound_reload_without_init_mon() {
33253328
do_test_outbound_reload_without_init_mon(true);
@@ -3428,6 +3431,7 @@ fn do_test_inbound_reload_without_init_mon(use_0conf: bool, lock_commitment: boo
34283431
assert!(nodes[1].node.list_channels().is_empty());
34293432
}
34303433

3434+
#[cfg(not(feature = "safe_channels"))]
34313435
#[test]
34323436
fn test_inbound_reload_without_init_mon() {
34333437
do_test_inbound_reload_without_init_mon(true, true);
@@ -3767,6 +3771,7 @@ fn do_test_inverted_mon_completion_order(
37673771
expect_payment_sent(&nodes[0], payment_preimage, None, true, true);
37683772
}
37693773

3774+
#[cfg(not(feature = "safe_channels"))]
37703775
#[test]
37713776
fn test_inverted_mon_completion_order() {
37723777
do_test_inverted_mon_completion_order(true, true);
@@ -3969,6 +3974,7 @@ fn do_test_durable_preimages_on_closed_channel(
39693974
}
39703975
}
39713976

3977+
#[cfg(not(feature = "safe_channels"))]
39723978
#[test]
39733979
fn test_durable_preimages_on_closed_channel() {
39743980
do_test_durable_preimages_on_closed_channel(true, true, true);
@@ -4093,6 +4099,7 @@ fn do_test_reload_mon_update_completion_actions(close_during_reload: bool) {
40934099
send_payment(&nodes[1], &[&nodes[2]], 100_000);
40944100
}
40954101

4102+
#[cfg(not(feature = "safe_channels"))]
40964103
#[test]
40974104
fn test_reload_mon_update_completion_actions() {
40984105
do_test_reload_mon_update_completion_actions(true);
@@ -4459,6 +4466,7 @@ fn do_test_partial_claim_mon_update_compl_actions(reload_a: bool, reload_b: bool
44594466
assert!(!get_monitor!(nodes[3], chan_4_id).get_stored_preimages().contains_key(&payment_hash));
44604467
}
44614468

4469+
#[cfg(not(feature = "safe_channels"))]
44624470
#[test]
44634471
fn test_partial_claim_mon_update_compl_actions() {
44644472
do_test_partial_claim_mon_update_compl_actions(true, true);

lightning/src/ln/channel.rs

Lines changed: 21 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2153,7 +2153,7 @@ where
21532153
// Not having a signing session implies they've already sent `splice_locked`,
21542154
// which must always come after the initial commitment signed is sent.
21552155
.unwrap_or(true);
2156-
let res = if has_negotiated_pending_splice && !session_received_commitment_signed {
2156+
let res: Result<(Option<ChannelMonitor<<<SP as Deref>::Target as SignerProvider>::EcdsaSigner>>, Option<ChannelMonitorUpdate>), ChannelError> = if has_negotiated_pending_splice && !session_received_commitment_signed {
21572157
funded_channel
21582158
.splice_initial_commitment_signed(msg, fee_estimator, logger)
21592159
.map(|monitor_update_opt| (None, monitor_update_opt))
@@ -6045,6 +6045,7 @@ where
60456045
should_broadcast: broadcast,
60466046
}],
60476047
channel_id: Some(self.channel_id()),
6048+
encoded_channel: None,
60486049
};
60496050
Some((self.get_counterparty_node_id(), funding_txo, self.channel_id(), update))
60506051
} else {
@@ -7276,6 +7277,7 @@ where
72767277
payment_info,
72777278
}],
72787279
channel_id: Some(self.context.channel_id()),
7280+
encoded_channel: None,
72797281
};
72807282

72817283
if !self.context.channel_state.can_generate_new_commitment() {
@@ -7417,6 +7419,7 @@ where
74177419
Vec::new(),
74187420
Vec::new(),
74197421
);
7422+
monitor_update.encoded_channel = Some(self.encode());
74207423
UpdateFulfillCommitFetch::NewClaim { monitor_update, htlc_value_msat }
74217424
},
74227425
UpdateFulfillFetch::DuplicateClaim {} => UpdateFulfillCommitFetch::DuplicateClaim {},
@@ -7892,14 +7895,15 @@ where
78927895
&self.context.channel_id(), pending_splice_funding.get_funding_txo().unwrap().txid);
78937896

78947897
self.context.latest_monitor_update_id += 1;
7895-
let monitor_update = ChannelMonitorUpdate {
7898+
let mut monitor_update = ChannelMonitorUpdate {
78967899
update_id: self.context.latest_monitor_update_id,
78977900
updates: vec![ChannelMonitorUpdateStep::RenegotiatedFunding {
78987901
channel_parameters: pending_splice_funding.channel_transaction_parameters.clone(),
78997902
holder_commitment_tx,
79007903
counterparty_commitment_tx,
79017904
}],
79027905
channel_id: Some(self.context.channel_id()),
7906+
encoded_channel: None,
79037907
};
79047908

79057909
self.context
@@ -7909,6 +7913,7 @@ where
79097913
.received_commitment_signed();
79107914
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
79117915

7916+
monitor_update.encoded_channel = Some(self.encode());
79127917
Ok(self.push_ret_blockable_mon_update(monitor_update))
79137918
}
79147919

@@ -8165,6 +8170,7 @@ where
81658170
update_id: self.context.latest_monitor_update_id,
81668171
updates: vec![update],
81678172
channel_id: Some(self.context.channel_id()),
8173+
encoded_channel: None,
81688174
};
81698175

81708176
self.context.expecting_peer_commitment_signed = false;
@@ -8217,6 +8223,7 @@ where
82178223
Vec::new(),
82188224
Vec::new(),
82198225
);
8226+
monitor_update.encoded_channel = Some(self.encode());
82208227
return Ok(self.push_ret_blockable_mon_update(monitor_update));
82218228
}
82228229

@@ -8270,6 +8277,7 @@ where
82708277
update_id: self.context.latest_monitor_update_id + 1, // We don't increment this yet!
82718278
updates: Vec::new(),
82728279
channel_id: Some(self.context.channel_id()),
8280+
encoded_channel: None,
82738281
};
82748282

82758283
let mut htlc_updates = Vec::new();
@@ -8346,7 +8354,7 @@ where
83468354
// `ChannelMonitorUpdate` to the user, making this one redundant, however
83478355
// there's no harm in including the extra `ChannelMonitorUpdateStep` here.
83488356
// We do not bother to track and include `payment_info` here, however.
8349-
let fulfill = self.get_update_fulfill_htlc(
8357+
let fulfill: UpdateFulfillFetch = self.get_update_fulfill_htlc(
83508358
htlc_id,
83518359
*payment_preimage,
83528360
None,
@@ -8360,6 +8368,8 @@ where
83608368
unreachable!()
83618369
};
83628370
update_fulfill_count += 1;
8371+
8372+
additional_monitor_update.encoded_channel = Some(self.encode());
83638373
monitor_update.updates.append(&mut additional_monitor_update.updates);
83648374
None
83658375
},
@@ -8418,6 +8428,8 @@ where
84188428
update_add_count, update_fulfill_count, update_fail_count);
84198429

84208430
self.monitor_updating_paused(false, true, false, Vec::new(), Vec::new(), Vec::new());
8431+
8432+
monitor_update.encoded_channel = Some(self.encode());
84218433
(self.push_ret_blockable_mon_update(monitor_update), htlcs_to_fail)
84228434
} else {
84238435
(None, Vec::new())
@@ -8534,6 +8546,7 @@ where
85348546
secret: msg.per_commitment_secret,
85358547
}],
85368548
channel_id: Some(self.context.channel_id()),
8549+
encoded_channel: None,
85378550
};
85388551

85398552
// Update state now that we've passed all the can-fail calls...
@@ -8759,6 +8772,7 @@ where
87598772
};
87608773
macro_rules! return_with_htlcs_to_fail {
87618774
($htlcs_to_fail: expr) => {
8775+
monitor_update.encoded_channel = Some(self.encode());
87628776
if !release_monitor {
87638777
self.context
87648778
.blocked_monitor_updates
@@ -10384,6 +10398,7 @@ where
1038410398
scriptpubkey: self.get_closing_scriptpubkey(),
1038510399
}],
1038610400
channel_id: Some(self.context.channel_id()),
10401+
encoded_channel: Some(self.encode()),
1038710402
};
1038810403
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
1038910404
self.push_ret_blockable_mon_update(monitor_update)
@@ -11153,6 +11168,7 @@ where
1115311168
funding_txid: funding_txo.txid,
1115411169
}],
1115511170
channel_id: Some(self.context.channel_id()),
11171+
encoded_channel: Some(self.encode()),
1115611172
};
1115711173
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
1115811174
let monitor_update = self.push_ret_blockable_mon_update(monitor_update);
@@ -12712,6 +12728,7 @@ where
1271212728
update_id: self.context.latest_monitor_update_id,
1271312729
updates: vec![update],
1271412730
channel_id: Some(self.context.channel_id()),
12731+
encoded_channel: Some(self.encode()),
1271512732
};
1271612733
self.context.channel_state.set_awaiting_remote_revoke();
1271712734
monitor_update
@@ -12958,6 +12975,7 @@ where
1295812975
scriptpubkey: self.get_closing_scriptpubkey(),
1295912976
}],
1296012977
channel_id: Some(self.context.channel_id()),
12978+
encoded_channel: Some(self.encode()),
1296112979
};
1296212980
self.monitor_updating_paused(false, false, false, Vec::new(), Vec::new(), Vec::new());
1296312981
self.push_ret_blockable_mon_update(monitor_update)

lightning/src/ln/channel_open_tests.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2095,6 +2095,7 @@ pub fn test_batch_channel_open() {
20952095
)));
20962096
}
20972097

2098+
#[cfg(not(feature = "safe_channels"))]
20982099
#[xtest(feature = "_externalize_tests")]
20992100
pub fn test_close_in_funding_batch() {
21002101
// This test ensures that if one of the channels
@@ -2183,6 +2184,7 @@ pub fn test_close_in_funding_batch() {
21832184
assert!(nodes[0].node.list_channels().is_empty());
21842185
}
21852186

2187+
#[cfg(not(feature = "safe_channels"))]
21862188
#[xtest(feature = "_externalize_tests")]
21872189
pub fn test_batch_funding_close_after_funding_signed() {
21882190
let chanmon_cfgs = create_chanmon_cfgs(3);

0 commit comments

Comments
 (0)