Skip to content

Commit

Permalink
Handle PeerStorageRetrieval in ChannelManager
Browse files Browse the repository at this point in the history
Ensure ChannelManager properly handles peer_storage_retrieval.

 - Write internal_peer_storage_retreival to verify if we recv correct peer storage.
 - Send error if we get invalid peer_storage data.
  • Loading branch information
Aditya Sharma authored and adi2011 committed Feb 27, 2025
1 parent 2d560fc commit f58d3ea
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 9 deletions.
2 changes: 1 addition & 1 deletion lightning-background-processor/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1087,7 +1087,7 @@ mod tests {
use lightning::routing::gossip::{NetworkGraph, P2PGossipSync};
use lightning::routing::router::{CandidateRouteHop, DefaultRouter, Path, RouteHop};
use lightning::routing::scoring::{ChannelUsage, LockableScore, ScoreLookUp, ScoreUpdate};
use lightning::sign::{ChangeDestinationSource, InMemorySigner, KeysManager};
use lightning::sign::{ChangeDestinationSource, InMemorySigner, KeysManager, NodeSigner};
use lightning::types::features::{ChannelFeatures, NodeFeatures};
use lightning::types::payment::PaymentHash;
use lightning::util::config::UserConfig;
Expand Down
3 changes: 2 additions & 1 deletion lightning-liquidity/tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
#![allow(unused_macros)]

use lightning::chain::Filter;
use lightning::sign::EntropySource;
use lightning::sign::{EntropySource, NodeSigner};

use bitcoin::blockdata::constants::{genesis_block, ChainHash};
use bitcoin::blockdata::transaction::Transaction;
Expand Down Expand Up @@ -431,6 +431,7 @@ pub(crate) fn create_liquidity_node(
logger.clone(),
fee_estimator.clone(),
kv_store.clone(),
keys_manager.get_peer_storage_key(),
));
let best_block = BestBlock::from_network(network);
let chain_params = ChainParameters { network, best_block };
Expand Down
37 changes: 30 additions & 7 deletions lightning/src/ln/channelmanager.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ use crate::types::payment::{PaymentHash, PaymentPreimage, PaymentSecret};
use crate::ln::channel::{self, Channel, ChannelError, ChannelUpdateStatus, FundedChannel, ShutdownResult, UpdateFulfillCommitFetch, OutboundV1Channel, ReconnectionMsg, InboundV1Channel, WithChannelContext};
#[cfg(any(dual_funding, splicing))]
use crate::ln::channel::PendingV2Channel;
use crate::ln::our_peer_storage::OurPeerStorage;
use crate::ln::channel_state::ChannelDetails;
use crate::types::features::{Bolt12InvoiceFeatures, ChannelFeatures, ChannelTypeFeatures, InitFeatures, NodeFeatures};
#[cfg(any(feature = "_test_utils", test))]
Expand Down Expand Up @@ -78,8 +79,8 @@ use crate::onion_message::async_payments::{AsyncPaymentsMessage, HeldHtlcAvailab
use crate::onion_message::dns_resolution::HumanReadableName;
use crate::onion_message::messenger::{Destination, MessageRouter, Responder, ResponseInstruction, MessageSendInstructions};
use crate::onion_message::offers::{OffersMessage, OffersMessageHandler};
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
use crate::sign::ecdsa::EcdsaChannelSigner;
use crate::sign::{EntropySource, NodeSigner, Recipient, SignerProvider};
use crate::util::config::{ChannelConfig, ChannelConfigUpdate, ChannelConfigOverrides, UserConfig};
use crate::util::wakers::{Future, Notifier};
use crate::util::scid_utils::fake_scid;
Expand Down Expand Up @@ -8296,15 +8297,37 @@ This indicates a bug inside LDK. Please report this error at https://github.com/
}
}

fn internal_peer_storage_retrieval(&self, counterparty_node_id: PublicKey, _msg: msgs::PeerStorageRetrieval) -> Result<(), MsgHandleErrInternal> {
// TODO: Decrypt and check if have any stale or missing ChannelMonitor.
fn internal_peer_storage_retrieval(&self, counterparty_node_id: PublicKey, msg: msgs::PeerStorageRetrieval) -> Result<(), MsgHandleErrInternal> {
// TODO: Check if have any stale or missing ChannelMonitor.
let logger = WithContext::from(&self.logger, Some(counterparty_node_id), None, None);

log_debug!(logger, "Received unexpected peer_storage_retrieval from {}. This is unusual since we do not yet distribute peer storage. Sending a warning.", log_pubkey!(counterparty_node_id));
if msg.data.len() < 16 {
log_debug!(logger, "Invalid YourPeerStorage received from {}", log_pubkey!(counterparty_node_id));
return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(
"Invalid peer_storage_retrieval message received.".into(),
), ChannelId([0; 32])));
}

let mut res = vec![0; msg.data.len() - 16];
let our_peerstorage_encryption_key = self.node_signer.get_peer_storage_key();
let mut cyphertext_with_key = Vec::with_capacity(msg.data.len() + our_peerstorage_encryption_key.len());
cyphertext_with_key.extend(msg.data.clone());
cyphertext_with_key.extend_from_slice(&our_peerstorage_encryption_key);

Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(
"Invalid peer_storage_retrieval message received.".into(),
), ChannelId([0; 32])))
match OurPeerStorage::decrypt_our_peer_storage(&mut res, cyphertext_with_key.as_slice()) {
Ok(()) => {
// Decryption successful, the plaintext is now stored in `res`.
log_debug!(logger, "Received a peer storage from peer {}", log_pubkey!(counterparty_node_id));
}
Err(_) => {
log_debug!(logger, "Invalid YourPeerStorage received from {}", log_pubkey!(counterparty_node_id));

return Err(MsgHandleErrInternal::from_chan_no_close(ChannelError::Warn(
"Invalid peer_storage_retrieval message received.".into(),
), ChannelId([0; 32])));
}
}
Ok(())
}

fn internal_peer_storage(&self, counterparty_node_id: PublicKey, msg: msgs::PeerStorage) -> Result<(), MsgHandleErrInternal> {
Expand Down

0 comments on commit f58d3ea

Please sign in to comment.