+
+ /// Gets a reference to the latest copy of a given ChannelMonitor given a &Key, if any has been
+ /// registered.
+ ///
+ /// The returned value contains a lock on this object, and other calls into this object will
+ /// almost certainly block until the returned value is dropped!
+ pub fn get_monitor_ref_by_key<'a>(&'a self, key: &Key) -> Option<ManyChannelMonitorLock<'a, Key, ChanSigner>> {
+ // Rust doesn't natively allow self-referential structs, and the only way to return a
+ // reference to something inside our Mutex is to return a struct that contains the lock and
+ // a reference to something pulled out of said lock.
+ // To avoid this, we have to fall back to some use of unsafe, but luckily its incredibly
+ // trivial - we simply Box up the MutexGuard and Box::leak() it, ensuring that its sitting
+ // in our heap without Rust having any reference to drop it.
+ // Then, we do a map lookup against the raw pointer, either returning a
+ // ManyChannelMonitorMonRef (which will drop the lock by recreating the Box when it gets
+ // dropped), or we will recreate the Box immediately and drop the lock before returning
+ // None.
+ //
+ // The returned ManyChannelMonitorMonRef is templated by a lifetime for which &self is
+ // valid, ensuring this object cannot be dropped until after the returned value is.
+ let lock = Box::new(self.monitors.lock().unwrap());
+ let lock_ptr: *mut MutexGuard<HashMap<Key, ChannelMonitor<ChanSigner>>> = Box::leak(lock);
+ let mon = unsafe { (*lock_ptr).get(key) };
+ if let Some(monitor) = mon {
+ Some(ManyChannelMonitorLock { lock_ptr, monitor })
+ } else {
+ let _ = unsafe { Box::from_raw(lock_ptr) };
+ // Drop the lock again
+ None
+ }
+ }