Skip to content

Commit b798c8e

Browse files
Aditya SharmaAditya Sharma
Aditya Sharma
authored and
Aditya Sharma
committed
lightning: Handle peer storage message, it's persistance and send it to the respective peer upon reconnection.
1 parent 63f2a3d commit b798c8e

File tree

2 files changed

+125
-4
lines changed

2 files changed

+125
-4
lines changed

lightning/src/chain/channelmonitor.rs

+31-2
Original file line numberDiff line numberDiff line change
@@ -544,6 +544,9 @@ pub(crate) enum ChannelMonitorUpdateStep {
544544
ShutdownScript {
545545
scriptpubkey: ScriptBuf,
546546
},
547+
LatestPeerStorage {
548+
data: Vec<u8>,
549+
},
547550
}
548551

549552
impl ChannelMonitorUpdateStep {
@@ -555,6 +558,7 @@ impl ChannelMonitorUpdateStep {
555558
ChannelMonitorUpdateStep::CommitmentSecret { .. } => "CommitmentSecret",
556559
ChannelMonitorUpdateStep::ChannelForceClosed { .. } => "ChannelForceClosed",
557560
ChannelMonitorUpdateStep::ShutdownScript { .. } => "ShutdownScript",
561+
ChannelMonitorUpdateStep::LatestPeerStorage { .. } => "LatestPeerStorage",
558562
}
559563
}
560564
}
@@ -588,6 +592,9 @@ impl_writeable_tlv_based_enum_upgradable!(ChannelMonitorUpdateStep,
588592
(5, ShutdownScript) => {
589593
(0, scriptpubkey, required),
590594
},
595+
(6, LatestPeerStorage) => {
596+
(0, data, required_vec),
597+
},
591598
);
592599

593600
/// Details about the balance(s) available for spending once the channel appears on chain.
@@ -835,6 +842,8 @@ pub(crate) struct ChannelMonitorImpl<Signer: WriteableEcdsaChannelSigner> {
835842
/// revoked.
836843
payment_preimages: HashMap<PaymentHash, PaymentPreimage>,
837844

845+
peer_storage: Vec<u8>,
846+
838847
// Note that `MonitorEvent`s MUST NOT be generated during update processing, only generated
839848
// during chain data processing. This prevents a race in `ChainMonitor::update_channel` (and
840849
// presumably user implementations thereof as well) where we update the in-memory channel
@@ -1110,6 +1119,7 @@ impl<Signer: WriteableEcdsaChannelSigner> Writeable for ChannelMonitorImpl<Signe
11101119
(15, self.counterparty_fulfilled_htlcs, required),
11111120
(17, self.initial_counterparty_commitment_info, option),
11121121
(19, self.channel_id, required),
1122+
(21, self.peer_storage, required_vec),
11131123
});
11141124

11151125
Ok(())
@@ -1289,7 +1299,7 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
12891299
confirmed_commitment_tx_counterparty_output: None,
12901300
htlcs_resolved_on_chain: Vec::new(),
12911301
spendable_txids_confirmed: Vec::new(),
1292-
1302+
peer_storage: Vec::new(),
12931303
best_block,
12941304
counterparty_node_id: Some(counterparty_node_id),
12951305
initial_counterparty_commitment_info: None,
@@ -1406,6 +1416,11 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitor<Signer> {
14061416
self.inner.lock().unwrap().channel_id()
14071417
}
14081418

1419+
/// Fets peer_storage of this peer.
1420+
pub fn get_peer_storage(&self) -> Vec<u8> {
1421+
self.inner.lock().unwrap().peer_storage()
1422+
}
1423+
14091424
/// Gets a list of txids, with their output scripts (in the order they appear in the
14101425
/// transaction), which we must learn about spends of via block_connected().
14111426
pub fn get_outputs_to_watch(&self) -> Vec<(Txid, Vec<(u32, ScriptBuf)>)> {
@@ -2700,6 +2715,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
27002715
}
27012716
}
27022717

2718+
fn update_peer_storage(&mut self, new_data: Vec<u8>) {
2719+
self.peer_storage = new_data;
2720+
}
2721+
27032722
fn generate_claimable_outpoints_and_watch_outputs(&mut self) -> (Vec<PackageTemplate>, Vec<TransactionOutputs>) {
27042723
let funding_outp = HolderFundingOutput::build(
27052724
self.funding_redeemscript.clone(),
@@ -2869,6 +2888,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
28692888
panic!("Attempted to replace shutdown script {} with {}", shutdown_script, scriptpubkey);
28702889
}
28712890
},
2891+
ChannelMonitorUpdateStep::LatestPeerStorage { data } => {
2892+
log_trace!(logger, "Updating ChannelMonitor with latest recieved PeerStorage");
2893+
self.update_peer_storage(data.clone());
2894+
}
28722895
}
28732896
}
28742897

@@ -2900,6 +2923,10 @@ impl<Signer: WriteableEcdsaChannelSigner> ChannelMonitorImpl<Signer> {
29002923
&self.funding_info
29012924
}
29022925

2926+
pub fn peer_storage(&self) -> Vec<u8> {
2927+
self.peer_storage.clone()
2928+
}
2929+
29032930
pub fn channel_id(&self) -> ChannelId {
29042931
self.channel_id
29052932
}
@@ -4601,6 +4628,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
46014628
let mut counterparty_fulfilled_htlcs = Some(new_hash_map());
46024629
let mut initial_counterparty_commitment_info = None;
46034630
let mut channel_id = None;
4631+
let mut peer_storage = Some(Vec::new());
46044632
read_tlv_fields!(reader, {
46054633
(1, funding_spend_confirmed, option),
46064634
(3, htlcs_resolved_on_chain, optional_vec),
@@ -4612,6 +4640,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
46124640
(15, counterparty_fulfilled_htlcs, option),
46134641
(17, initial_counterparty_commitment_info, option),
46144642
(19, channel_id, option),
4643+
(21, peer_storage, optional_vec),
46154644
});
46164645

46174646
// Monitors for anchor outputs channels opened in v0.0.116 suffered from a bug in which the
@@ -4676,7 +4705,7 @@ impl<'a, 'b, ES: EntropySource, SP: SignerProvider> ReadableArgs<(&'a ES, &'b SP
46764705
confirmed_commitment_tx_counterparty_output,
46774706
htlcs_resolved_on_chain: htlcs_resolved_on_chain.unwrap(),
46784707
spendable_txids_confirmed: spendable_txids_confirmed.unwrap(),
4679-
4708+
peer_storage: peer_storage.unwrap(),
46804709
best_block,
46814710
counterparty_node_id,
46824711
initial_counterparty_commitment_info,

lightning/src/ln/channelmanager.rs

+94-2
Original file line numberDiff line numberDiff line change
@@ -1401,6 +1401,7 @@ where
14011401
node_signer: NS,
14021402
signer_provider: SP,
14031403

1404+
peer_storage: RwLock<HashMap<PublicKey, Vec<u8>>>,
14041405
logger: L,
14051406
}
14061407

@@ -2483,7 +2484,7 @@ where
24832484
entropy_source,
24842485
node_signer,
24852486
signer_provider,
2486-
2487+
peer_storage: RwLock::new(HashMap::new()),
24872488
logger,
24882489
}
24892490
}
@@ -6432,6 +6433,73 @@ where
64326433
}
64336434
}
64346435

6436+
fn internal_peer_storage(&self, counterparty_node_id: &PublicKey, msg: &msgs::PeerStorageMessage) -> Result<(), ()> {
6437+
let per_peer_state = self.per_peer_state.read().unwrap();
6438+
let peer_state_mutex = match per_peer_state.get(counterparty_node_id) {
6439+
Some(peer_state_mutex) => peer_state_mutex,
6440+
None => return Err(()),
6441+
};
6442+
6443+
// Check if we have any channels with the peer (Currently we only provide the servie to peers we have a channel with).
6444+
let chan_info = self.list_channels_with_counterparty(counterparty_node_id);
6445+
if chan_info.is_empty() {
6446+
return Err(());
6447+
}
6448+
6449+
// Send ChannelMonitor Update.
6450+
let sorted_chan_info: Vec<ChannelDetails> = chan_info.iter().cloned().collect();
6451+
let sorted_chan_info = {
6452+
let mut sorted_vec: Vec<ChannelDetails> = sorted_chan_info;
6453+
sorted_vec.sort_by_cached_key(|s| s.funding_txo.unwrap().get_txid());
6454+
sorted_vec
6455+
};
6456+
6457+
let mut found_funded_chan = false;
6458+
for chan in &sorted_chan_info {
6459+
if let Some(funding_txo) = chan.funding_txo {
6460+
found_funded_chan = true;
6461+
let peer_storage_update = ChannelMonitorUpdate {
6462+
update_id: CLOSED_CHANNEL_UPDATE_ID,
6463+
counterparty_node_id: None,
6464+
updates: vec![ChannelMonitorUpdateStep::LatestPeerStorage {
6465+
data: msg.data.clone(),
6466+
}],
6467+
channel_id: Some(chan.channel_id),
6468+
};
6469+
// Since channel monitor is already loaded so we do not need to push this onto background event.
6470+
let update_res: ChannelMonitorUpdateStatus = self.chain_monitor.update_channel(funding_txo, &peer_storage_update);
6471+
if update_res != ChannelMonitorUpdateStatus::Completed {
6472+
log_error!(WithContext::from(&self.logger, None, Some(chan.channel_id)),
6473+
"Critical error: failed to update channel monitor with latest peer storage {:?}: {:?}",
6474+
msg.data, update_res);
6475+
}
6476+
break;
6477+
}
6478+
}
6479+
6480+
if !found_funded_chan {
6481+
return Err(());
6482+
}
6483+
6484+
6485+
// Update the store.
6486+
let mut peer_storage = self.peer_storage.write().unwrap();
6487+
peer_storage.insert(*counterparty_node_id, msg.data.clone());
6488+
6489+
let mut peer_state_lock = peer_state_mutex.lock().unwrap();
6490+
let peer_state = &mut *peer_state_lock;
6491+
6492+
// Send ACK.
6493+
peer_state.pending_msg_events.push(events::MessageSendEvent::SendYourPeerStorageMessage {
6494+
node_id: counterparty_node_id.clone(),
6495+
msg: msgs::YourPeerStorageMessage {
6496+
data: msg.data.clone()
6497+
},
6498+
});
6499+
6500+
Ok(())
6501+
}
6502+
64356503
fn internal_funding_signed(&self, counterparty_node_id: &PublicKey, msg: &msgs::FundingSigned) -> Result<(), MsgHandleErrInternal> {
64366504
let best_block = *self.best_block.read().unwrap();
64376505
let per_peer_state = self.per_peer_state.read().unwrap();
@@ -8743,6 +8811,13 @@ where
87438811
}
87448812

87458813
fn handle_peer_storage(&self, counterparty_node_id: &PublicKey, msg: &msgs::PeerStorageMessage) {
8814+
match self.internal_peer_storage(counterparty_node_id, msg) {
8815+
Ok(_) => {},
8816+
Err(_err) => {
8817+
let logger = WithContext::from(&self.logger, Some(*counterparty_node_id), None);
8818+
log_debug!(logger, "Could not store Peer Storage for peer {}", log_pubkey!(counterparty_node_id));
8819+
},
8820+
}
87468821
}
87478822

87488823
fn handle_your_peer_storage(&self, counterparty_node_id: &PublicKey, msg: &msgs::YourPeerStorageMessage) {
@@ -9104,6 +9179,19 @@ where
91049179
}
91059180
}
91069181
}
9182+
9183+
let peer_storage = self.peer_storage.read().unwrap();
9184+
9185+
if let Some(value) = peer_storage.get(counterparty_node_id) {
9186+
log_debug!(logger, "Generating peerstorage for {}", log_pubkey!(counterparty_node_id));
9187+
9188+
pending_msg_events.push(events::MessageSendEvent::SendYourPeerStorageMessage {
9189+
node_id: counterparty_node_id.clone(),
9190+
msg: msgs::YourPeerStorageMessage {
9191+
data: value.clone()
9192+
},
9193+
});
9194+
}
91079195
}
91089196

91099197
return NotifyOption::SkipPersistHandleEvents;
@@ -10391,6 +10479,7 @@ where
1039110479
let mut channel_closures = VecDeque::new();
1039210480
let mut close_background_events = Vec::new();
1039310481
let mut funding_txo_to_channel_id = hash_map_with_capacity(channel_count as usize);
10482+
let mut peer_storage_dir: HashMap<PublicKey, Vec<u8>> = HashMap::new();
1039410483
for _ in 0..channel_count {
1039510484
let mut channel: Channel<SP> = Channel::read(reader, (
1039610485
&args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
@@ -10400,6 +10489,9 @@ where
1040010489
funding_txo_to_channel_id.insert(funding_txo, channel.context.channel_id());
1040110490
funding_txo_set.insert(funding_txo.clone());
1040210491
if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
10492+
// Load Peer_storage from ChannelMonitor to memory.
10493+
peer_storage_dir.insert(channel.context.get_counterparty_node_id(), monitor.get_peer_storage());
10494+
1040310495
if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
1040410496
channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
1040510497
channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||
@@ -11209,7 +11301,7 @@ where
1120911301
entropy_source: args.entropy_source,
1121011302
node_signer: args.node_signer,
1121111303
signer_provider: args.signer_provider,
11212-
11304+
peer_storage: RwLock::new(peer_storage_dir),
1121311305
logger: args.logger,
1121411306
default_configuration: args.default_config,
1121511307
};

0 commit comments

Comments
 (0)