Skip to content

Commit 793de5f

Browse files
authored
Merge pull request #819 from TheBlueMatt/2021-03-810-rebased
Change ChannelManager deserialization to return an optional blockhash
2 parents 03a5189 + 8550bd4 commit 793de5f

File tree

10 files changed

+59
-43
lines changed

10 files changed

+59
-43
lines changed

fuzz/src/chanmon_consistency.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -126,7 +126,7 @@ impl chain::Watch<EnforcingSigner> for TestChainMonitor {
126126
hash_map::Entry::Occupied(entry) => entry,
127127
hash_map::Entry::Vacant(_) => panic!("Didn't have monitor on update call"),
128128
};
129-
let deserialized_monitor = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::
129+
let deserialized_monitor = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::
130130
read(&mut Cursor::new(&map_entry.get().1), &OnlyReadsKeysInterface {}).unwrap().1;
131131
deserialized_monitor.update_monitor(&update, &&TestBroadcaster{}, &&FuzzEstimator{}, &self.logger).unwrap();
132132
let mut ser = VecWriter(Vec::new());
@@ -337,7 +337,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
337337
let mut monitors = HashMap::new();
338338
let mut old_monitors = $old_monitors.latest_monitors.lock().unwrap();
339339
for (outpoint, (update_id, monitor_ser)) in old_monitors.drain() {
340-
monitors.insert(outpoint, <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
340+
monitors.insert(outpoint, <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&monitor_ser), &OnlyReadsKeysInterface {}).expect("Failed to read monitor").1);
341341
chain_monitor.latest_monitors.lock().unwrap().insert(outpoint, (update_id, monitor_ser));
342342
}
343343
let mut monitor_refs = HashMap::new();
@@ -355,7 +355,7 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
355355
channel_monitors: monitor_refs,
356356
};
357357

358-
(<(BlockHash, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor)
358+
(<(Option<BlockHash>, ChanMan)>::read(&mut Cursor::new(&$ser.0), read_args).expect("Failed to read manager").1, chain_monitor)
359359
} }
360360
}
361361

fuzz/src/chanmon_deser.rs

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -25,11 +25,13 @@ impl Writer for VecWriter {
2525

2626
#[inline]
2727
pub fn do_test<Out: test_logger::Output>(data: &[u8], _out: Out) {
28-
if let Ok((latest_block_hash, monitor)) = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) {
28+
if let Ok((Some(latest_block_hash), monitor)) = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(data), &OnlyReadsKeysInterface {}) {
2929
let mut w = VecWriter(Vec::new());
3030
monitor.write(&mut w).unwrap();
31-
let deserialized_copy = <(BlockHash, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap();
32-
assert!(latest_block_hash == deserialized_copy.0);
31+
let deserialized_copy = <(Option<BlockHash>, channelmonitor::ChannelMonitor<EnforcingSigner>)>::read(&mut Cursor::new(&w.0), &OnlyReadsKeysInterface {}).unwrap();
32+
if let Some(deserialized) = deserialized_copy.0 {
33+
assert!(latest_block_hash == deserialized);
34+
}
3335
assert!(monitor == deserialized_copy.1);
3436
}
3537
}

lightning-block-sync/src/init.rs

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -73,12 +73,12 @@ BlockSourceResult<ValidatedBlockHeader> {
7373
/// ) {
7474
/// // Read a serialized channel monitor paired with the block hash when it was persisted.
7575
/// let serialized_monitor = "...";
76-
/// let (monitor_block_hash, mut monitor) = <(BlockHash, ChannelMonitor<S>)>::read(
76+
/// let (monitor_block_hash_option, mut monitor) = <(Option<BlockHash>, ChannelMonitor<S>)>::read(
7777
/// &mut Cursor::new(&serialized_monitor), keys_manager).unwrap();
7878
///
7979
/// // Read the channel manager paired with the block hash when it was persisted.
8080
/// let serialized_manager = "...";
81-
/// let (manager_block_hash, mut manager) = {
81+
/// let (manager_block_hash_option, mut manager) = {
8282
/// let read_args = ChannelManagerReadArgs::new(
8383
/// keys_manager,
8484
/// fee_estimator,
@@ -88,17 +88,20 @@ BlockSourceResult<ValidatedBlockHeader> {
8888
/// config,
8989
/// vec![&mut monitor],
9090
/// );
91-
/// <(BlockHash, ChannelManager<S, &ChainMonitor<S, &C, &T, &F, &L, &P>, &T, &K, &F, &L>)>::read(
91+
/// <(Option<BlockHash>, ChannelManager<S, &ChainMonitor<S, &C, &T, &F, &L, &P>, &T, &K, &F, &L>)>::read(
9292
/// &mut Cursor::new(&serialized_manager), read_args).unwrap()
9393
/// };
9494
///
9595
/// // Synchronize any channel monitors and the channel manager to be on the best block.
9696
/// let mut cache = UnboundedCache::new();
9797
/// let mut monitor_listener = (monitor, &*tx_broadcaster, &*fee_estimator, &*logger);
98-
/// let listeners = vec![
99-
/// (monitor_block_hash, &mut monitor_listener as &mut dyn chain::Listen),
100-
/// (manager_block_hash, &mut manager as &mut dyn chain::Listen),
101-
/// ];
98+
/// let mut listeners = vec![];
99+
/// if let Some(monitor_block_hash) = monitor_block_hash_option {
100+
/// listeners.push((monitor_block_hash, &mut monitor_listener as &mut dyn chain::Listen))
101+
/// }
102+
/// if let Some(manager_block_hash) = manager_block_hash_option {
103+
/// listeners.push((manager_block_hash, &mut manager as &mut dyn chain::Listen))
104+
/// }
102105
/// let chain_tip = init::synchronize_listeners(
103106
/// block_source, Network::Bitcoin, &mut cache, listeners).await.unwrap();
104107
///

lightning-persister/src/lib.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ impl FilesystemPersister {
124124
if contents.is_err() { return Err(ChannelMonitorUpdateErr::PermanentFailure); }
125125

126126
if let Ok((_, loaded_monitor)) =
127-
<(BlockHash, ChannelMonitor<Keys::Signer>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
127+
<(Option<BlockHash>, ChannelMonitor<Keys::Signer>)>::read(&mut Cursor::new(&contents.unwrap()), keys) {
128128
res.insert(OutPoint { txid: txid.unwrap(), index: index.unwrap() }, loaded_monitor);
129129
} else {
130130
return Err(ChannelMonitorUpdateErr::PermanentFailure);

lightning/src/chain/channelmonitor.rs

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -620,7 +620,7 @@ impl Readable for ChannelMonitorUpdateStep {
620620
/// reloaded at deserialize-time. Thus, you must ensure that, when handling events, all events
621621
/// gotten are fully handled before re-serializing the new state.
622622
///
623-
/// Note that the deserializer is only implemented for (Sha256dHash, ChannelMonitor), which
623+
/// Note that the deserializer is only implemented for (Option<BlockHash>, ChannelMonitor), which
624624
/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
625625
/// the "reorg path" (ie disconnecting blocks until you find a common ancestor from both the
626626
/// returned block hash and the the current chain and then reconnecting blocks to get to the
@@ -2492,7 +2492,7 @@ where
24922492
const MAX_ALLOC_SIZE: usize = 64*1024;
24932493

24942494
impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
2495-
for (BlockHash, ChannelMonitor<Signer>) {
2495+
for (Option<BlockHash>, ChannelMonitor<Signer>) {
24962496
fn read<R: ::std::io::Read>(reader: &mut R, keys_manager: &'a K) -> Result<Self, DecodeError> {
24972497
macro_rules! unwrap_obj {
24982498
($key: expr) => {
@@ -2735,7 +2735,13 @@ impl<'a, Signer: Sign, K: KeysInterface<Signer = Signer>> ReadableArgs<&'a K>
27352735
let mut secp_ctx = Secp256k1::new();
27362736
secp_ctx.seeded_randomize(&keys_manager.get_secure_random_bytes());
27372737

2738-
Ok((last_block_hash.clone(), ChannelMonitor {
2738+
let last_seen_block_hash = if last_block_hash == Default::default() {
2739+
None
2740+
} else {
2741+
Some(last_block_hash)
2742+
};
2743+
2744+
Ok((last_seen_block_hash, ChannelMonitor {
27392745
inner: Mutex::new(ChannelMonitorImpl {
27402746
latest_update_id,
27412747
commitment_transaction_number_obscure_factor,

lightning/src/ln/chanmon_update_fail_tests.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -106,7 +106,7 @@ fn test_monitor_and_persister_update_fail() {
106106
let monitor = monitors.get(&outpoint).unwrap();
107107
let mut w = test_utils::TestVecWriter(Vec::new());
108108
monitor.write(&mut w).unwrap();
109-
let new_monitor = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
109+
let new_monitor = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
110110
&mut ::std::io::Cursor::new(&w.0), &test_utils::OnlyReadsKeysInterface {}).unwrap().1;
111111
assert!(new_monitor == *monitor);
112112
let chain_mon = test_utils::TestChainMonitor::new(Some(&chain_source), &chanmon_cfgs[0].tx_broadcaster, &logger, &chanmon_cfgs[0].fee_estimator, &persister, &node_cfgs[0].keys_manager);

lightning/src/ln/channelmanager.rs

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -380,7 +380,7 @@ pub type SimpleRefChannelManager<'a, 'b, 'c, 'd, 'e, M, T, F, L> = ChannelManage
380380
/// ChannelMonitors passed by reference to read(), those channels will be force-closed based on the
381381
/// ChannelMonitor state and no funds will be lost (mod on-chain transaction fees).
382382
///
383-
/// Note that the deserializer is only implemented for (Sha256dHash, ChannelManager), which
383+
/// Note that the deserializer is only implemented for (Option<BlockHash>, ChannelManager), which
384384
/// tells you the last block hash which was block_connect()ed. You MUST rescan any blocks along
385385
/// the "reorg path" (ie call block_disconnected() until you get to a common block and then call
386386
/// block_connected() to step towards your best block) upon deserialization before using the
@@ -3925,7 +3925,7 @@ impl<Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref> Writeable f
39253925
/// At a high-level, the process for deserializing a ChannelManager and resuming normal operation
39263926
/// is:
39273927
/// 1) Deserialize all stored ChannelMonitors.
3928-
/// 2) Deserialize the ChannelManager by filling in this struct and calling <(Sha256dHash,
3928+
/// 2) Deserialize the ChannelManager by filling in this struct and calling <(Option<BlockHash>,
39293929
/// ChannelManager)>::read(reader, args).
39303930
/// This may result in closing some Channels if the ChannelMonitor is newer than the stored
39313931
/// ChannelManager state to ensure no loss of funds. Thus, transactions may be broadcasted.
@@ -4006,21 +4006,21 @@ impl<'a, Signer: 'a + Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
40064006
// Implement ReadableArgs for an Arc'd ChannelManager to make it a bit easier to work with the
40074007
// SipmleArcChannelManager type:
40084008
impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4009-
ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, Arc<ChannelManager<Signer, M, T, K, F, L>>)
4009+
ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (Option<BlockHash>, Arc<ChannelManager<Signer, M, T, K, F, L>>)
40104010
where M::Target: chain::Watch<Signer>,
40114011
T::Target: BroadcasterInterface,
40124012
K::Target: KeysInterface<Signer = Signer>,
40134013
F::Target: FeeEstimator,
40144014
L::Target: Logger,
40154015
{
40164016
fn read<R: ::std::io::Read>(reader: &mut R, args: ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>) -> Result<Self, DecodeError> {
4017-
let (blockhash, chan_manager) = <(BlockHash, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
4017+
let (blockhash, chan_manager) = <(Option<BlockHash>, ChannelManager<Signer, M, T, K, F, L>)>::read(reader, args)?;
40184018
Ok((blockhash, Arc::new(chan_manager)))
40194019
}
40204020
}
40214021

40224022
impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
4023-
ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (BlockHash, ChannelManager<Signer, M, T, K, F, L>)
4023+
ReadableArgs<ChannelManagerReadArgs<'a, Signer, M, T, K, F, L>> for (Option<BlockHash>, ChannelManager<Signer, M, T, K, F, L>)
40244024
where M::Target: chain::Watch<Signer>,
40254025
T::Target: BroadcasterInterface,
40264026
K::Target: KeysInterface<Signer = Signer>,
@@ -4172,7 +4172,12 @@ impl<'a, Signer: Sign, M: Deref, T: Deref, K: Deref, F: Deref, L: Deref>
41724172
//TODO: Broadcast channel update for closed channels, but only after we've made a
41734173
//connection or two.
41744174

4175-
Ok((last_block_hash.clone(), channel_manager))
4175+
let last_seen_block_hash = if last_block_hash == Default::default() {
4176+
None
4177+
} else {
4178+
Some(last_block_hash)
4179+
};
4180+
Ok((last_seen_block_hash, channel_manager))
41764181
}
41774182
}
41784183

lightning/src/ln/functional_test_utils.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -172,7 +172,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
172172
for (_, old_monitor) in old_monitors.iter() {
173173
let mut w = test_utils::TestVecWriter(Vec::new());
174174
old_monitor.write(&mut w).unwrap();
175-
let (_, deserialized_monitor) = <(BlockHash, ChannelMonitor<EnforcingSigner>)>::read(
175+
let (_, deserialized_monitor) = <(Option<BlockHash>, ChannelMonitor<EnforcingSigner>)>::read(
176176
&mut ::std::io::Cursor::new(&w.0), self.keys_manager).unwrap();
177177
deserialized_monitors.push(deserialized_monitor);
178178
}
@@ -188,7 +188,7 @@ impl<'a, 'b, 'c> Drop for Node<'a, 'b, 'c> {
188188

189189
let mut w = test_utils::TestVecWriter(Vec::new());
190190
self.node.write(&mut w).unwrap();
191-
<(BlockHash, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
191+
<(Option<BlockHash>, ChannelManager<EnforcingSigner, &test_utils::TestChainMonitor, &test_utils::TestBroadcaster, &test_utils::TestKeysInterface, &test_utils::TestFeeEstimator, &test_utils::TestLogger>)>::read(&mut ::std::io::Cursor::new(w.0), ChannelManagerReadArgs {
192192
default_config: UserConfig::default(),
193193
keys_manager: self.keys_manager,
194194
fee_estimator: &test_utils::TestFeeEstimator { sat_per_kw: 253 },

0 commit comments

Comments
 (0)