Skip to content

Commit 680731c

Browse files
committed
fixup: Enable ChainMonitor to distribute PeerStorage
1 parent 09c7748 commit 680731c

File tree

7 files changed

+70
-26
lines changed

7 files changed

+70
-26
lines changed

lightning-background-processor/src/lib.rs

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ use lightning::onion_message::messenger::AOnionMessenger;
3636
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
3737
use lightning::routing::scoring::{ScoreUpdate, WriteableScore};
3838
use lightning::routing::utxo::UtxoLookup;
39+
use lightning::sign::EntropySource;
3940
use lightning::util::logger::Logger;
4041
use lightning::util::persist::Persister;
4142
#[cfg(feature = "std")]
@@ -911,8 +912,11 @@ impl BackgroundProcessor {
911912
P: 'static + Deref + Send + Sync,
912913
EH: 'static + EventHandler + Send,
913914
PS: 'static + Deref + Send,
915+
ES: 'static + Deref + Send,
914916
M: 'static
915-
+ Deref<Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P>>
917+
+ Deref<
918+
Target = ChainMonitor<<CM::Target as AChannelManager>::Signer, CF, T, F, L, P, ES>,
919+
>
916920
+ Send
917921
+ Sync,
918922
CM: 'static + Deref + Send + Sync,
@@ -935,6 +939,7 @@ impl BackgroundProcessor {
935939
L::Target: 'static + Logger,
936940
P::Target: 'static + Persist<<CM::Target as AChannelManager>::Signer>,
937941
PS::Target: 'static + Persister<'a, CM, L, S>,
942+
ES::Target: 'static + EntropySource,
938943
CM::Target: AChannelManager + Send + Sync,
939944
OM::Target: AOnionMessenger + Send + Sync,
940945
PM::Target: APeerManager + Send + Sync,
@@ -1160,6 +1165,7 @@ mod tests {
11601165
Arc<test_utils::TestFeeEstimator>,
11611166
Arc<test_utils::TestLogger>,
11621167
Arc<FilesystemStore>,
1168+
Arc<KeysManager>,
11631169
>;
11641170

11651171
type PGS = Arc<
@@ -1569,6 +1575,7 @@ mod tests {
15691575
logger.clone(),
15701576
fee_estimator.clone(),
15711577
kv_store.clone(),
1578+
keys_manager.clone(),
15721579
keys_manager.get_peer_storage_key(),
15731580
));
15741581
let best_block = BestBlock::from_network(network);

lightning-liquidity/tests/common/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -101,6 +101,7 @@ type ChainMonitor = chainmonitor::ChainMonitor<
101101
Arc<test_utils::TestFeeEstimator>,
102102
Arc<test_utils::TestLogger>,
103103
Arc<FilesystemStore>,
104+
Arc<KeysManager>,
104105
>;
105106

106107
type PGS = Arc<
@@ -431,6 +432,7 @@ pub(crate) fn create_liquidity_node(
431432
logger.clone(),
432433
fee_estimator.clone(),
433434
kv_store.clone(),
435+
keys_manager.clone(),
434436
keys_manager.get_peer_storage_key(),
435437
));
436438
let best_block = BestBlock::from_network(network);

lightning/src/chain/chainmonitor.rs

Lines changed: 22 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ use crate::ln::types::ChannelId;
3535
use crate::ln::msgs::{self, BaseMessageHandler, Init, MessageSendEvent};
3636
use crate::ln::our_peer_storage::OurPeerStorage;
3737
use crate::sign::ecdsa::EcdsaChannelSigner;
38-
use crate::sign::PeerStorageKey;
38+
use crate::sign::{EntropySource, PeerStorageKey};
3939
use crate::events::{self, Event, EventHandler, ReplayEvent};
4040
use crate::util::logger::{Logger, WithContext};
4141
use crate::util::errors::APIError;
@@ -234,19 +234,21 @@ impl<ChannelSigner: EcdsaChannelSigner> Deref for LockedChannelMonitor<'_, Chann
234234
/// [`ChannelManager`]: crate::ln::channelmanager::ChannelManager
235235
/// [module-level documentation]: crate::chain::chainmonitor
236236
/// [`rebroadcast_pending_claims`]: Self::rebroadcast_pending_claims
237-
pub struct ChainMonitor<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
237+
pub struct ChainMonitor<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref>
238238
where C::Target: chain::Filter,
239239
T::Target: BroadcasterInterface,
240240
F::Target: FeeEstimator,
241241
L::Target: Logger,
242242
P::Target: Persist<ChannelSigner>,
243+
ES::Target: EntropySource,
243244
{
244245
monitors: RwLock<HashMap<ChannelId, MonitorHolder<ChannelSigner>>>,
245246
chain_source: Option<C>,
246247
broadcaster: T,
247248
logger: L,
248249
fee_estimator: F,
249250
persister: P,
251+
entropy_source: ES,
250252
/// "User-provided" (ie persistence-completion/-failed) [`MonitorEvent`]s. These came directly
251253
/// from the user and not from a [`ChannelMonitor`].
252254
pending_monitor_events: Mutex<Vec<(OutPoint, ChannelId, Vec<MonitorEvent>, PublicKey)>>,
@@ -261,12 +263,13 @@ pub struct ChainMonitor<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F
261263
our_peerstorage_encryption_key: PeerStorageKey,
262264
}
263265

264-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P>
266+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref> ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
265267
where C::Target: chain::Filter,
266268
T::Target: BroadcasterInterface,
267269
F::Target: FeeEstimator,
268270
L::Target: Logger,
269271
P::Target: Persist<ChannelSigner>,
272+
ES::Target: EntropySource,
270273
{
271274
/// Dispatches to per-channel monitors, which are responsible for updating their on-chain view
272275
/// of a channel and reacting accordingly based on transactions in the given chain data. See
@@ -400,14 +403,15 @@ where C::Target: chain::Filter,
400403
/// **Important**: This key should not be set arbitrarily or changed after initialization. The same key
401404
/// is obtained by the `ChannelManager` through `KeyMananger` to decrypt peer backups.
402405
/// Using an inconsistent or incorrect key will result in the inability to decrypt previously encrypted backups.
403-
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P, our_peerstorage_encryption_key: PeerStorageKey) -> Self {
406+
pub fn new(chain_source: Option<C>, broadcaster: T, logger: L, feeest: F, persister: P, entropy_source: ES, our_peerstorage_encryption_key: PeerStorageKey) -> Self {
404407
Self {
405408
monitors: RwLock::new(new_hash_map()),
406409
chain_source,
407410
broadcaster,
408411
logger,
409412
fee_estimator: feeest,
410413
persister,
414+
entropy_source,
411415
pending_monitor_events: Mutex::new(Vec::new()),
412416
highest_chain_height: AtomicUsize::new(0),
413417
event_notifier: Notifier::new(),
@@ -697,19 +701,20 @@ where C::Target: chain::Filter,
697701
fn send_peer_storage(&self, their_node_id: PublicKey) {
698702
// TODO: Serialize `ChannelMonitor`s inside `our_peer_storage`.
699703

700-
let our_peer_storage = OurPeerStorage::create_from_data(self.our_peerstorage_encryption_key.clone(), Vec::new());
704+
let our_peer_storage = OurPeerStorage::create_from_data(self.our_peerstorage_encryption_key.clone(), Vec::new(), self.entropy_source.get_secure_random_bytes());
701705
log_debug!(self.logger, "Sending Peer Storage from chainmonitor");
702706
self.pending_send_only_events.lock().unwrap().push(MessageSendEvent::SendPeerStorage { node_id: their_node_id,
703707
msg: msgs::PeerStorage { data: our_peer_storage.encrypted_data() } })
704708
}
705709
}
706710

707-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> BaseMessageHandler for ChainMonitor<ChannelSigner, C, T, F, L, P>
711+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref> BaseMessageHandler for ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
708712
where C::Target: chain::Filter,
709713
T::Target: BroadcasterInterface,
710714
F::Target: FeeEstimator,
711715
L::Target: Logger,
712716
P::Target: Persist<ChannelSigner>,
717+
ES::Target: EntropySource,
713718
{
714719
fn get_and_clear_pending_msg_events(&self) -> Vec<MessageSendEvent> {
715720
let mut pending_events = self.pending_send_only_events.lock().unwrap();
@@ -729,14 +734,15 @@ where C::Target: chain::Filter,
729734
fn peer_connected(&self, _their_node_id: PublicKey, _msg: &Init, _inbound: bool) -> Result<(), ()> { Ok(()) }
730735
}
731736

732-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
733-
chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P>
737+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref>
738+
chain::Listen for ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
734739
where
735740
C::Target: chain::Filter,
736741
T::Target: BroadcasterInterface,
737742
F::Target: FeeEstimator,
738743
L::Target: Logger,
739744
P::Target: Persist<ChannelSigner>,
745+
ES::Target: EntropySource,
740746
{
741747
fn filtered_block_connected(&self, header: &Header, txdata: &TransactionData, height: u32) {
742748
log_debug!(self.logger, "New best block {} at height {} provided via block_connected", header.block_hash(), height);
@@ -764,14 +770,15 @@ where
764770
}
765771
}
766772

767-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref>
768-
chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P>
773+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref>
774+
chain::Confirm for ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
769775
where
770776
C::Target: chain::Filter,
771777
T::Target: BroadcasterInterface,
772778
F::Target: FeeEstimator,
773779
L::Target: Logger,
774780
P::Target: Persist<ChannelSigner>,
781+
ES::Target: EntropySource,
775782
{
776783
fn transactions_confirmed(&self, header: &Header, txdata: &TransactionData, height: u32) {
777784
log_debug!(self.logger, "{} provided transactions confirmed at height {} in block {}", txdata.len(), height, header.block_hash());
@@ -824,13 +831,14 @@ where
824831
}
825832
}
826833

827-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref >
828-
chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P>
834+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref , T: Deref , F: Deref , L: Deref , P: Deref, ES: Deref>
835+
chain::Watch<ChannelSigner> for ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
829836
where C::Target: chain::Filter,
830837
T::Target: BroadcasterInterface,
831838
F::Target: FeeEstimator,
832839
L::Target: Logger,
833840
P::Target: Persist<ChannelSigner>,
841+
ES::Target: EntropySource,
834842
{
835843
fn watch_channel(&self, channel_id: ChannelId, monitor: ChannelMonitor<ChannelSigner>) -> Result<ChannelMonitorUpdateStatus, ()> {
836844
let logger = WithChannelMonitor::from(&self.logger, &monitor, None);
@@ -963,12 +971,13 @@ where C::Target: chain::Filter,
963971
}
964972
}
965973

966-
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P>
974+
impl<ChannelSigner: EcdsaChannelSigner, C: Deref, T: Deref, F: Deref, L: Deref, P: Deref, ES: Deref> events::EventsProvider for ChainMonitor<ChannelSigner, C, T, F, L, P, ES>
967975
where C::Target: chain::Filter,
968976
T::Target: BroadcasterInterface,
969977
F::Target: FeeEstimator,
970978
L::Target: Logger,
971979
P::Target: Persist<ChannelSigner>,
980+
ES::Target: EntropySource,
972981
{
973982
/// Processes [`SpendableOutputs`] events produced from each [`ChannelMonitor`] upon maturity.
974983
///

lightning/src/ln/our_peer_storage.rs

Lines changed: 30 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,9 @@
1111
//! It supports encryption and decryption to maintain data integrity and security during
1212
//! transmission.
1313
//!
14+
use bitcoin::hashes::sha256::Hash as Sha256;
15+
use bitcoin::hashes::{Hash, HashEngine};
16+
1417
use crate::sign::PeerStorageKey;
1518

1619
use crate::crypto::chacha20poly1305rfc::ChaCha20Poly1305RFC;
@@ -63,40 +66,56 @@ impl OurPeerStorage {
6366
/// (serialised channel information), and returns a serialised [`OurPeerStorage`] as a `Vec<u8>`.
6467
///
6568
/// The resulting serialised data is intended to be directly used for transmission to the peers.
66-
pub fn create_from_data(key: PeerStorageKey, mut ser_channels: Vec<u8>) -> OurPeerStorage {
67-
let n = 0u64;
69+
pub fn create_from_data(
70+
key: PeerStorageKey, mut ser_channels: Vec<u8>, random_bytes: [u8; 32],
71+
) -> OurPeerStorage {
72+
let key_hash = Sha256::const_hash(&key.inner);
6873

6974
let plaintext_len = ser_channels.len();
7075

71-
let mut nonce = [0; 12];
72-
nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
76+
// Compute Sha256(Sha256(key) + random_bytes).
77+
let mut sha = Sha256::engine();
78+
sha.input(&key_hash.to_byte_array());
79+
sha.input(&random_bytes);
80+
81+
let mut nonce = [0u8; 12];
82+
nonce[4..].copy_from_slice(&Sha256::from_engine(sha).to_byte_array()[0..8]);
7383

7484
let mut chacha = ChaCha20Poly1305RFC::new(&key.inner, &nonce, b"");
7585
let mut tag = [0; 16];
7686
chacha.encrypt_full_message_in_place(&mut ser_channels[0..plaintext_len], &mut tag);
7787

7888
ser_channels.extend_from_slice(&tag);
7989

90+
// Append `random_bytes` in front of the encrypted_blob.
91+
ser_channels.splice(0..0, random_bytes);
8092
Self { encrypted_data: ser_channels }
8193
}
8294

8395
/// Decrypt `OurPeerStorage` using the `key`, result is stored inside the `res`.
8496
/// Returns an error if the the `cyphertext` is not correct.
8597
pub fn decrypt_our_peer_storage(mut self, key: PeerStorageKey) -> Result<Vec<u8>, ()> {
86-
const MIN_CYPHERTEXT_LEN: usize = 16;
98+
let key_hash = Sha256::const_hash(&key.inner);
99+
100+
// Length of tag + Length of random_bytes
101+
const MIN_CYPHERTEXT_LEN: usize = 16 + 32;
87102
let cyphertext_len = self.encrypted_data.len();
88103

89104
// Ensure the cyphertext is at least as large as the MIN_CYPHERTEXT_LEN.
90105
if cyphertext_len < MIN_CYPHERTEXT_LEN {
91106
return Err(());
92107
}
93108

94-
// Split the cyphertext into the encrypted data and the authentication tag.
95-
let (encrypted_data, tag) = self.encrypted_data.split_at_mut(cyphertext_len - 16);
109+
// Ciphertext is of the form: random_bytes(32 bytes) + encrypted_data + tag(16 bytes).
110+
let (data_mut, tag) = self.encrypted_data.split_at_mut(cyphertext_len - 16);
111+
let (random_bytes, encrypted_data) = data_mut.split_at_mut(32);
112+
113+
let mut sha = Sha256::engine();
114+
sha.input(&key_hash.to_byte_array());
115+
sha.input(random_bytes);
96116

97-
let n = 0u64;
98-
let mut nonce = [0; 12];
99-
nonce[4..].copy_from_slice(&n.to_le_bytes()[..]);
117+
let mut nonce = [0u8; 12];
118+
nonce[4..].copy_from_slice(&Sha256::from_engine(sha).to_byte_array()[0..8]);
100119

101120
let mut chacha = ChaCha20Poly1305RFC::new(&key.inner, &nonce, b"");
102121

@@ -105,6 +124,7 @@ impl OurPeerStorage {
105124
}
106125

107126
self.encrypted_data.truncate(cyphertext_len - 16);
127+
self.encrypted_data.drain(0..32);
108128

109129
Ok(self.encrypted_data)
110130
}

lightning/src/ln/peer_handler.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -721,7 +721,7 @@ pub type SimpleArcPeerManager<SD, M, T, F, C, L, CF, S> = PeerManager<
721721
Arc<L>,
722722
IgnoringMessageHandler,
723723
Arc<KeysManager>,
724-
Arc<ChainMonitor<InMemorySigner, Arc<CF>, Arc<T>, Arc<F>, Arc<L>, Arc<S>>>,
724+
Arc<ChainMonitor<InMemorySigner, Arc<CF>, Arc<T>, Arc<F>, Arc<L>, Arc<S>, Arc<KeysManager>>>,
725725
>;
726726

727727
/// SimpleRefPeerManager is a type alias for a PeerManager reference, and is the reference
@@ -743,7 +743,7 @@ pub type SimpleRefPeerManager<
743743
&'logger L,
744744
IgnoringMessageHandler,
745745
&'c KeysManager,
746-
&'j ChainMonitor<&'a M, C, &'b T, &'c F, &'logger L, &'c KeysManager>,
746+
&'j ChainMonitor<&'a M, C, &'b T, &'c F, &'logger L, &'c KeysManager, &'c KeysManager>,
747747
>;
748748

749749

lightning/src/util/anchor_channel_reserves.rs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,7 @@ use crate::ln::chan_utils::max_htlcs;
2929
use crate::ln::channelmanager::AChannelManager;
3030
use crate::prelude::new_hash_set;
3131
use crate::sign::ecdsa::EcdsaChannelSigner;
32+
use crate::sign::EntropySource;
3233
use crate::types::features::ChannelTypeFeatures;
3334
use crate::util::logger::Logger;
3435
use bitcoin::constants::WITNESS_SCALE_FACTOR;
@@ -276,6 +277,7 @@ pub fn can_support_additional_anchor_channel<
276277
EstimatorRef: Deref,
277278
LoggerRef: Deref,
278279
PersistRef: Deref,
280+
EntropySourceRef: Deref,
279281
ChainMonitorRef: Deref<
280282
Target = ChainMonitor<
281283
ChannelSigner,
@@ -284,6 +286,7 @@ pub fn can_support_additional_anchor_channel<
284286
EstimatorRef,
285287
LoggerRef,
286288
PersistRef,
289+
EntropySourceRef,
287290
>,
288291
>,
289292
>(
@@ -297,6 +300,7 @@ where
297300
EstimatorRef::Target: FeeEstimator,
298301
LoggerRef::Target: Logger,
299302
PersistRef::Target: Persist<ChannelSigner>,
303+
EntropySourceRef::Target: EntropySource,
300304
{
301305
let mut anchor_channels = new_hash_set();
302306
// Calculate the number of in-progress anchor channels by inspecting ChannelMonitors with balance.

lightning/src/util/test_utils.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -407,6 +407,7 @@ pub struct TestChainMonitor<'a> {
407407
&'a TestFeeEstimator,
408408
&'a TestLogger,
409409
&'a dyn SyncPersist,
410+
&'a TestKeysInterface,
410411
>,
411412
pub keys_manager: &'a TestKeysInterface,
412413
/// If this is set to Some(), the next update_channel call (not watch_channel) must be a
@@ -435,6 +436,7 @@ impl<'a> TestChainMonitor<'a> {
435436
logger,
436437
fee_estimator,
437438
persister,
439+
keys_manager,
438440
keys_manager.get_peer_storage_key(),
439441
),
440442
keys_manager,

0 commit comments

Comments
 (0)