Skip to content

Commit cc26ace

Browse files
Aditya SharmaAditya Sharma
authored andcommitted
lightning: Add struct for building OurPeerStorage, it gets updated everytime a LatestCounterpartyCommitmentTxn update is sent. It would be encrypted and sent to our peers.
1 parent e53ae91 commit cc26ace

File tree

5 files changed

+316
-4
lines changed

5 files changed

+316
-4
lines changed

lightning/src/chain/channelmonitor.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ use crate::ln::msgs::DecodeError;
3838
use crate::ln::channel_keys::{DelayedPaymentKey, DelayedPaymentBasepoint, HtlcBasepoint, HtlcKey, RevocationKey, RevocationBasepoint};
3939
use crate::ln::chan_utils::{self,CommitmentTransaction, CounterpartyCommitmentSecrets, HTLCOutputInCommitment, HTLCClaim, ChannelTransactionParameters, HolderCommitmentTransaction, TxCreationKeys};
4040
use crate::ln::channelmanager::{HTLCSource, SentHTLCId};
41+
use crate::ln::our_peer_storage::StubChannelMonitor;
42+
use crate::ln::features::ChannelTypeFeatures;
4143
use crate::chain;
4244
use crate::chain::{BestBlock, WatchedOutput};
4345
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
@@ -1532,6 +1534,19 @@ impl<Signer: EcdsaChannelSigner> ChannelMonitor<Signer> {
15321534
self.inner.lock().unwrap().get_latest_update_id()
15331535
}
15341536

1537+
/// Gets the latest claiming info from the ChannelMonitor to update our PeerStorageBackup.
1538+
pub(crate) fn get_latest_commitment_txn_and_its_claiming_info(&self) -> Option<(Txid, Vec<(HTLCOutputInCommitment, Option<std::boxed::Box<HTLCSource>>)>, Option<(u64, PublicKey, Option<PublicKey>)>)> {
1539+
let lock = self.inner.lock().unwrap();
1540+
if let Some(latest_txid) = lock.current_counterparty_commitment_txid {
1541+
return Some((
1542+
latest_txid, lock.counterparty_claimable_outpoints.get(&latest_txid).unwrap().clone(),
1543+
lock.their_cur_per_commitment_points
1544+
))
1545+
}
1546+
1547+
None
1548+
}
1549+
15351550
/// Gets the funding transaction outpoint of the channel this ChannelMonitor is monitoring for.
15361551
pub fn get_funding_txo(&self) -> (OutPoint, ScriptBuf) {
15371552
self.inner.lock().unwrap().get_funding_txo().clone()

lightning/src/ln/channel.rs

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2071,6 +2071,18 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
20712071
self.update_time_counter
20722072
}
20732073

2074+
pub fn get_commitment_secret(&self) -> CounterpartyCommitmentSecrets {
2075+
self.commitment_secrets.clone()
2076+
}
2077+
2078+
pub fn get_channel_keys_id(&self) -> [u8;32] {
2079+
self.channel_keys_id
2080+
}
2081+
2082+
pub fn get_commitment_txn_number_obscure_factor(&self) -> u64 {
2083+
get_commitment_transaction_number_obscure_factor(&self.get_holder_pubkeys().payment_point, &self.get_counterparty_pubkeys().payment_point, self.is_outbound())
2084+
}
2085+
20742086
pub fn get_latest_monitor_update_id(&self) -> u64 {
20752087
self.latest_monitor_update_id
20762088
}
@@ -2369,7 +2381,7 @@ impl<SP: Deref> ChannelContext<SP> where SP::Target: SignerProvider {
23692381
height.checked_sub(self.funding_tx_confirmation_height).map_or(0, |c| c + 1)
23702382
}
23712383

2372-
fn get_holder_selected_contest_delay(&self) -> u16 {
2384+
pub fn get_holder_selected_contest_delay(&self) -> u16 {
23732385
self.channel_transaction_parameters.holder_selected_contest_delay
23742386
}
23752387

lightning/src/ln/channelmanager.rs

Lines changed: 57 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -40,13 +40,14 @@ use crate::blinded_path::payment::{BlindedPaymentPath, Bolt12OfferContext, Bolt1
4040
use crate::chain;
4141
use crate::chain::{Confirm, ChannelMonitorUpdateStatus, Watch, BestBlock};
4242
use crate::chain::chaininterface::{BroadcasterInterface, ConfirmationTarget, FeeEstimator, LowerBoundedFeeEstimator};
43-
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, WithChannelMonitor, ChannelMonitorUpdateStep, HTLC_FAIL_BACK_BUFFER, CLTV_CLAIM_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, ANTI_REORG_DELAY, MonitorEvent, CLOSED_CHANNEL_UPDATE_ID};
43+
use crate::chain::channelmonitor::{ChannelMonitor, ChannelMonitorUpdate, ChannelMonitorUpdateStep, MonitorEvent, WithChannelMonitor, ANTI_REORG_DELAY, CLOSED_CHANNEL_UPDATE_ID, CLTV_CLAIM_BUFFER, HTLC_FAIL_BACK_BUFFER, LATENCY_GRACE_PERIOD_BLOCKS, STUB_CHANNEL_UPDATE_IDENTIFIER};
4444
use crate::chain::transaction::{OutPoint, TransactionData};
4545
use crate::events;
4646
use crate::events::{Event, EventHandler, EventsProvider, MessageSendEvent, MessageSendEventsProvider, ClosureReason, HTLCDestination, PaymentFailureReason, ReplayEvent};
4747
// Since this struct is returned in `list_channels` methods, expose it here in case users want to
4848
// construct one themselves.
4949
use crate::ln::inbound_payment;
50+
use crate::ln::our_peer_storage::{OurPeerStorage, StubChannelMonitor};
5051
use crate::ln::types::{ChannelId, PaymentHash, PaymentPreimage, PaymentSecret};
5152
use crate::ln::channel::{self, Channel, ChannelPhase, ChannelContext, ChannelError, ChannelUpdateStatus, ShutdownResult, UnfundedChannelContext, UpdateFulfillCommitFetch, OutboundV1Channel, InboundV1Channel, WithChannelContext};
5253
use crate::ln::channel_state::ChannelDetails;
@@ -6875,6 +6876,8 @@ where
68756876
if let Some(raa_blocker) = raa_blocker_opt {
68766877
peer_state.actions_blocking_raa_monitor_updates.entry(chan_id).or_insert_with(Vec::new).push(raa_blocker);
68776878
}
6879+
6880+
let _ = self.our_peer_storage.write().unwrap().update_state_from_monitor_update(chan.context.channel_id(), monitor_update.clone());
68786881
if !during_init {
68796882
handle_new_monitor_update!(self, prev_hop.outpoint, monitor_update, peer_state_lock,
68806883
peer_state, per_peer_state, chan);
@@ -8014,7 +8017,18 @@ where
80148017
let mut pending_events = self.pending_events.lock().unwrap();
80158018
emit_channel_ready_event!(pending_events, chan);
80168019
}
8017-
8020+
// Update Peer Storage.
8021+
let counterparty_channel_parameters = chan.context.channel_transaction_parameters.counterparty_parameters.as_ref().unwrap();
8022+
let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
8023+
let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
8024+
let stub_chan = StubChannelMonitor::new(chan.context.channel_id(), chan.context.get_funding_txo().unwrap(), chan.context.get_value_satoshis(),
8025+
chan.context.get_channel_keys_id(), chan.context.get_commitment_secret(),
8026+
chan.context.get_counterparty_node_id(), counterparty_delayed_payment_base_key, counterparty_htlc_base_key,
8027+
chan.context.get_holder_selected_contest_delay(),
8028+
chan.context.get_commitment_txn_number_obscure_factor(), None,
8029+
None, chan.context.channel_transaction_parameters.channel_type_features.clone(),
8030+
self.current_best_block());
8031+
self.our_peer_storage.write().unwrap().stub_channel(stub_chan);
80188032
Ok(())
80198033
} else {
80208034
try_chan_phase_entry!(self, Err(ChannelError::close(
@@ -8362,6 +8376,7 @@ where
83628376
let funding_txo = chan.context.get_funding_txo();
83638377
let monitor_update_opt = try_chan_phase_entry!(self, chan.commitment_signed(&msg, &&logger), chan_phase_entry);
83648378
if let Some(monitor_update) = monitor_update_opt {
8379+
let _ = self.our_peer_storage.write().unwrap().update_state_from_monitor_update(chan.context.channel_id(), monitor_update.clone());
83658380
handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update, peer_state_lock,
83668381
peer_state, per_peer_state, chan);
83678382
}
@@ -8562,9 +8577,14 @@ where
85628577
} else { false };
85638578
let (htlcs_to_fail, monitor_update_opt) = try_chan_phase_entry!(self,
85648579
chan.revoke_and_ack(&msg, &self.fee_estimator, &&logger, mon_update_blocked), chan_phase_entry);
8580+
8581+
let mut our_peer_storage = self.our_peer_storage.write().unwrap();
85658582
if let Some(monitor_update) = monitor_update_opt {
85668583
let funding_txo = funding_txo_opt
85678584
.expect("Funding outpoint must have been set for RAA handling to succeed");
8585+
8586+
let _ = our_peer_storage.update_state_from_monitor_update(chan.context.channel_id(), monitor_update.clone());
8587+
85688588
handle_new_monitor_update!(self, funding_txo, monitor_update,
85698589
peer_state_lock, peer_state, per_peer_state, chan);
85708590
}
@@ -8908,6 +8928,7 @@ where
89088928
}
89098929
if let Some(monitor_update) = monitor_opt {
89108930
has_monitor_update = true;
8931+
let _ = self.our_peer_storage.write().unwrap().update_state_from_monitor_update(chan.context.channel_id(), monitor_update.clone());
89118932

89128933
handle_new_monitor_update!(self, funding_txo.unwrap(), monitor_update,
89138934
peer_state_lock, peer_state, per_peer_state, chan);
@@ -10145,7 +10166,7 @@ where
1014510166
}
1014610167
channel.best_block_updated(height, header.time, self.chain_hash, &self.node_signer, &self.default_configuration, &&WithChannelContext::from(&self.logger, &channel.context, None))
1014710168
});
10148-
10169+
self.our_peer_storage.write().unwrap().update_best_block(header, height);
1014910170
macro_rules! max_time {
1015010171
($timestamp: expr) => {
1015110172
loop {
@@ -12326,6 +12347,8 @@ where
1232612347
let mut channel_closures = VecDeque::new();
1232712348
let mut close_background_events = Vec::new();
1232812349
let mut funding_txo_to_channel_id = hash_map_with_capacity(channel_count as usize);
12350+
let mut our_peer_storage: OurPeerStorage = OurPeerStorage::new();
12351+
1232912352
for _ in 0..channel_count {
1233012353
let mut channel: Channel<SP> = Channel::read(reader, (
1233112354
&args.entropy_source, &args.signer_provider, best_block_height, &provided_channel_type_features(&args.default_config)
@@ -12334,7 +12357,38 @@ where
1233412357
let funding_txo = channel.context.get_funding_txo().ok_or(DecodeError::InvalidValue)?;
1233512358
funding_txo_to_channel_id.insert(funding_txo, channel.context.channel_id());
1233612359
funding_txo_set.insert(funding_txo.clone());
12360+
let counterparty_channel_parameters = channel.context.channel_transaction_parameters.counterparty_parameters.as_ref().unwrap();
12361+
let counterparty_delayed_payment_base_key = counterparty_channel_parameters.pubkeys.delayed_payment_basepoint;
12362+
let counterparty_htlc_base_key = counterparty_channel_parameters.pubkeys.htlc_basepoint;
12363+
12364+
let stub_chan = StubChannelMonitor::new(
12365+
channel.context.channel_id(),
12366+
funding_txo,
12367+
channel.context.get_value_satoshis(),
12368+
channel.context.get_channel_keys_id(),
12369+
channel.context.get_commitment_secret(),
12370+
channel.context.get_counterparty_node_id(),
12371+
counterparty_delayed_payment_base_key,
12372+
counterparty_htlc_base_key,
12373+
channel.context.get_holder_selected_contest_delay(),
12374+
channel.context.get_commitment_txn_number_obscure_factor(),
12375+
None,
12376+
None,
12377+
channel.context.channel_transaction_parameters.channel_type_features.clone(),
12378+
BestBlock::new(best_block_hash.clone(), best_block_height.clone()),
12379+
);
12380+
our_peer_storage.stub_channel(stub_chan);
1233712381
if let Some(ref mut monitor) = args.channel_monitors.get_mut(&funding_txo) {
12382+
if let Some(latest_commitment_txn_info) = monitor.get_latest_commitment_txn_and_its_claiming_info() {
12383+
12384+
our_peer_storage.update_latest_state(monitor.channel_id(), latest_commitment_txn_info.0, latest_commitment_txn_info.2);
12385+
}
12386+
12387+
if monitor.get_latest_update_id() == STUB_CHANNEL_UPDATE_IDENTIFIER {
12388+
log_error!(logger, "ChannelMonitor for {} is stale and recovered from Peer Storage, it is not safe to run the node in normal mode.", monitor.channel_id());
12389+
return Err(DecodeError::DangerousValue);
12390+
}
12391+
1233812392
if channel.get_cur_holder_commitment_transaction_number() > monitor.get_cur_holder_commitment_number() ||
1233912393
channel.get_revoked_counterparty_commitment_transaction_number() > monitor.get_min_seen_secret() ||
1234012394
channel.get_cur_counterparty_commitment_transaction_number() > monitor.get_cur_counterparty_commitment_number() ||

lightning/src/ln/mod.rs

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,8 @@ pub mod chan_utils;
3030
pub mod features;
3131
pub mod script;
3232
pub mod types;
33+
pub mod fundrecoverer;
34+
pub mod our_peer_storage;
3335

3436
// TODO: These modules were moved from lightning-invoice and need to be better integrated into this
3537
// crate now:

0 commit comments

Comments
 (0)