1 use std::collections::{BTreeMap, HashSet};
5 use std::time::{Instant, SystemTime, UNIX_EPOCH};
7 use lightning::ln::msgs::{ChannelAnnouncement, ChannelUpdate, UnsignedChannelAnnouncement, UnsignedChannelUpdate};
8 use lightning::routing::gossip::NetworkGraph;
9 use lightning::util::ser::Readable;
10 use tokio_postgres::{Client, Connection, NoTls, Socket};
11 use tokio_postgres::tls::NoTlsStream;
13 use futures::StreamExt;
14 use lightning::log_info;
15 use lightning::util::logger::Logger;
18 use crate::serialization::MutatedProperties;
20 /// The delta set needs to be a BTreeMap so the keys are sorted.
21 /// That way, the scids in the response automatically grow monotonically
22 pub(super) type DeltaSet = BTreeMap<u64, ChannelDelta>;
24 pub(super) struct AnnouncementDelta {
26 pub(super) announcement: UnsignedChannelAnnouncement,
29 pub(super) struct UpdateDelta {
31 pub(super) update: UnsignedChannelUpdate,
34 pub(super) struct DirectedUpdateDelta {
35 pub(super) last_update_before_seen: Option<UnsignedChannelUpdate>,
36 pub(super) mutated_properties: MutatedProperties,
37 pub(super) latest_update_after_seen: Option<UpdateDelta>,
38 pub(super) serialization_update_flags: Option<u8>,
41 pub(super) struct ChannelDelta {
42 pub(super) announcement: Option<AnnouncementDelta>,
43 pub(super) updates: (Option<DirectedUpdateDelta>, Option<DirectedUpdateDelta>),
44 pub(super) first_bidirectional_updates_seen: Option<u32>,
45 /// The seen timestamp of the older of the two latest directional updates
46 pub(super) requires_reminder: bool,
49 impl Default for ChannelDelta {
50 fn default() -> Self {
53 updates: (None, None),
54 first_bidirectional_updates_seen: None,
55 requires_reminder: false,
60 impl Default for DirectedUpdateDelta {
61 fn default() -> Self {
63 last_update_before_seen: None,
64 mutated_properties: MutatedProperties::default(),
65 latest_update_after_seen: None,
66 serialization_update_flags: None,
71 pub(super) async fn connect_to_db() -> (Client, Connection<Socket, NoTlsStream>) {
72 let connection_config = config::db_connection_config();
73 connection_config.connect(NoTls).await.unwrap()
76 /// Fetch all the channel announcements that are presently in the network graph, regardless of
77 /// whether they had been seen before.
78 /// Also include all announcements for which the first update was announced
79 /// after `last_sync_timestamp`
80 pub(super) async fn fetch_channel_announcements<L: Deref>(delta_set: &mut DeltaSet, network_graph: Arc<NetworkGraph<L>>, client: &Client, last_sync_timestamp: u32, logger: L) where L::Target: Logger {
81 log_info!(logger, "Obtaining channel ids from network graph");
83 let read_only_graph = network_graph.read_only();
84 log_info!(logger, "Retrieved read-only network graph copy");
85 let channel_iterator = read_only_graph.channels().unordered_iter();
87 .filter(|c| c.1.announcement_message.is_some())
88 .map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
92 log_info!(logger, "Channel IDs: {:?}", channel_ids);
93 log_info!(logger, "Last sync timestamp: {}", last_sync_timestamp);
94 let last_sync_timestamp_float = last_sync_timestamp as f64;
96 log_info!(logger, "Obtaining corresponding database entries");
97 // get all the channel announcements that are currently in the network graph
98 let announcement_rows = client.query_raw("SELECT announcement_signed, seen FROM channel_announcements WHERE short_channel_id = any($1) ORDER BY short_channel_id ASC", [&channel_ids]).await.unwrap();
99 let mut pinned_rows = Box::pin(announcement_rows);
101 let mut announcement_count = 0;
102 while let Some(row_res) = pinned_rows.next().await {
103 let current_announcement_row = row_res.unwrap();
104 let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
105 let mut readable = Cursor::new(blob);
106 let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
108 let scid = unsigned_announcement.short_channel_id;
109 let current_seen_timestamp_object: SystemTime = current_announcement_row.get("seen");
110 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
112 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
113 (*current_channel_delta).announcement = Some(AnnouncementDelta {
114 announcement: unsigned_announcement,
115 seen: current_seen_timestamp,
118 announcement_count += 1;
120 log_info!(logger, "Fetched {} announcement rows", announcement_count);
123 // THIS STEP IS USED TO DETERMINE IF A CHANNEL SHOULD BE OMITTED FROM THE DELTA
125 log_info!(logger, "Annotating channel announcements whose oldest channel update in a given direction occurred after the last sync");
127 // — Obtain all updates, distinct by (scid, direction), ordered by seen DESC // to find the oldest update in a given direction
128 // — From those updates, select distinct by (scid), ordered by seen DESC (to obtain the newer one per direction)
129 // This will allow us to mark the first time updates in both directions were seen
131 // here is where the channels whose first update in either direction occurred after
132 // `last_seen_timestamp` are added to the selection
133 let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
134 [&channel_ids, &last_sync_timestamp_float];
135 let newer_oldest_directional_updates = client.query_raw("
137 SELECT DISTINCT ON (short_channel_id) *
139 SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
141 WHERE short_channel_id = any($1)
142 ORDER BY short_channel_id ASC, direction ASC, seen ASC
143 ) AS directional_last_seens
144 ORDER BY short_channel_id ASC, seen DESC
146 WHERE distinct_chans.seen >= TO_TIMESTAMP($2)
147 ", params).await.unwrap();
148 let mut pinned_updates = Box::pin(newer_oldest_directional_updates);
150 let mut newer_oldest_directional_update_count = 0;
151 while let Some(row_res) = pinned_updates.next().await {
152 let current_row = row_res.unwrap();
154 let scid: i64 = current_row.get("short_channel_id");
155 let current_seen_timestamp_object: SystemTime = current_row.get("seen");
156 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
158 // the newer of the two oldest seen directional updates came after last sync timestamp
159 let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
160 // first time a channel was seen in both directions
161 (*current_channel_delta).first_bidirectional_updates_seen = Some(current_seen_timestamp);
163 newer_oldest_directional_update_count += 1;
165 log_info!(logger, "Fetched {} update rows of the first update in a new direction", newer_oldest_directional_update_count);
169 // THIS STEP IS USED TO DETERMINE IF A REMINDER UPDATE SHOULD BE SENT
171 log_info!(logger, "Annotating channel announcements whose latest channel update in a given direction occurred more than six days ago");
173 // — Obtain all updates, distinct by (scid, direction), ordered by seen DESC
174 // — From those updates, select distinct by (scid), ordered by seen ASC (to obtain the older one per direction)
175 let reminder_threshold_timestamp = SystemTime::now().checked_sub(config::CHANNEL_REMINDER_AGE).unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as f64;
177 let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
178 [&channel_ids, &reminder_threshold_timestamp];
179 let older_latest_directional_updates = client.query_raw("
180 SELECT short_channel_id FROM (
181 SELECT DISTINCT ON (short_channel_id) *
183 SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
185 WHERE short_channel_id = any($1)
186 ORDER BY short_channel_id ASC, direction ASC, seen DESC
187 ) AS directional_last_seens
188 ORDER BY short_channel_id ASC, seen ASC
190 WHERE distinct_chans.seen <= TO_TIMESTAMP($2)
191 ", params).await.unwrap();
192 let mut pinned_updates = Box::pin(older_latest_directional_updates);
194 let mut older_latest_directional_update_count = 0;
195 while let Some(row_res) = pinned_updates.next().await {
196 let current_row = row_res.unwrap();
197 let scid: i64 = current_row.get("short_channel_id");
199 // annotate this channel as requiring that reminders be sent to the client
200 let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
202 // way might be able to get away with not using this
203 (*current_channel_delta).requires_reminder = true;
205 if let Some(current_channel_info) = network_graph.read_only().channel(scid as u64) {
206 if current_channel_info.one_to_two.is_none() || current_channel_info.two_to_one.is_none() {
207 // we don't send reminders if we don't have bidirectional update data
211 if let Some(info) = current_channel_info.one_to_two.as_ref() {
212 let flags: u8 = if info.enabled { 0 } else { 2 };
213 let current_update = (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default());
214 current_update.serialization_update_flags = Some(flags);
217 if let Some(info) = current_channel_info.two_to_one.as_ref() {
218 let flags: u8 = if info.enabled { 1 } else { 3 };
219 let current_update = (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default());
220 current_update.serialization_update_flags = Some(flags);
223 // we don't send reminders if we don't have the channel
226 older_latest_directional_update_count += 1;
228 log_info!(logger, "Fetched {} update rows of the latest update in the less recently updated direction", older_latest_directional_update_count);
232 pub(super) async fn fetch_channel_updates<L: Deref>(delta_set: &mut DeltaSet, client: &Client, last_sync_timestamp: u32, logger: L) where L::Target: Logger {
233 let start = Instant::now();
234 let last_sync_timestamp_float = last_sync_timestamp as f64;
236 // get the latest channel update in each direction prior to last_sync_timestamp, provided
237 // there was an update in either direction that happened after the last sync (to avoid
238 // collecting too many reference updates)
239 let reference_rows = client.query_raw("
240 SELECT id, direction, blob_signed FROM channel_updates
242 SELECT DISTINCT ON (short_channel_id, direction) id
244 WHERE seen < TO_TIMESTAMP($1) AND short_channel_id IN (
245 SELECT DISTINCT ON (short_channel_id) short_channel_id
247 WHERE seen >= TO_TIMESTAMP($1)
249 ORDER BY short_channel_id ASC, direction ASC, seen DESC
251 ", [last_sync_timestamp_float]).await.unwrap();
252 let mut pinned_rows = Box::pin(reference_rows);
254 log_info!(logger, "Fetched reference rows in {:?}", start.elapsed());
256 let mut last_seen_update_ids: Vec<i32> = Vec::new();
257 let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
258 let mut reference_row_count = 0;
260 while let Some(row_res) = pinned_rows.next().await {
261 let current_reference = row_res.unwrap();
262 let update_id: i32 = current_reference.get("id");
263 last_seen_update_ids.push(update_id);
264 non_intermediate_ids.insert(update_id);
266 let direction: bool = current_reference.get("direction");
267 let blob: Vec<u8> = current_reference.get("blob_signed");
268 let mut readable = Cursor::new(blob);
269 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
270 let scid = unsigned_channel_update.short_channel_id;
272 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
273 let update_delta = if !direction {
274 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
276 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
278 update_delta.last_update_before_seen = Some(unsigned_channel_update);
279 reference_row_count += 1;
282 log_info!(logger, "Processed {} reference rows (delta size: {}) in {:?}",
283 reference_row_count, delta_set.len(), start.elapsed());
285 // get all the intermediate channel updates
286 // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
287 // have been omitted)
289 let intermediate_updates = client.query_raw("
290 SELECT id, direction, blob_signed, seen
292 WHERE seen >= TO_TIMESTAMP($1)
293 ", [last_sync_timestamp_float]).await.unwrap();
294 let mut pinned_updates = Box::pin(intermediate_updates);
295 log_info!(logger, "Fetched intermediate rows in {:?}", start.elapsed());
297 let mut previous_scid = u64::MAX;
298 let mut previously_seen_directions = (false, false);
300 // let mut previously_seen_directions = (false, false);
301 let mut intermediate_update_count = 0;
302 while let Some(row_res) = pinned_updates.next().await {
303 let intermediate_update = row_res.unwrap();
304 let update_id: i32 = intermediate_update.get("id");
305 if non_intermediate_ids.contains(&update_id) {
308 intermediate_update_count += 1;
310 let direction: bool = intermediate_update.get("direction");
311 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
312 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
313 let blob: Vec<u8> = intermediate_update.get("blob_signed");
314 let mut readable = Cursor::new(blob);
315 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
317 let scid = unsigned_channel_update.short_channel_id;
318 if scid != previous_scid {
319 previous_scid = scid;
320 previously_seen_directions = (false, false);
323 // get the write configuration for this particular channel's directional details
324 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
325 let update_delta = if !direction {
326 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
328 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
332 // handle the latest deltas
333 if !direction && !previously_seen_directions.0 {
334 previously_seen_directions.0 = true;
335 update_delta.latest_update_after_seen = Some(UpdateDelta {
336 seen: current_seen_timestamp,
337 update: unsigned_channel_update.clone(),
339 } else if direction && !previously_seen_directions.1 {
340 previously_seen_directions.1 = true;
341 update_delta.latest_update_after_seen = Some(UpdateDelta {
342 seen: current_seen_timestamp,
343 update: unsigned_channel_update.clone(),
348 // determine mutations
349 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref() {
350 if unsigned_channel_update.flags != last_seen_update.flags {
351 update_delta.mutated_properties.flags = true;
353 if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
354 update_delta.mutated_properties.cltv_expiry_delta = true;
356 if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
357 update_delta.mutated_properties.htlc_minimum_msat = true;
359 if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
360 update_delta.mutated_properties.fee_base_msat = true;
362 if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
363 update_delta.mutated_properties.fee_proportional_millionths = true;
365 if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
366 update_delta.mutated_properties.htlc_maximum_msat = true;
370 log_info!(logger, "Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
373 pub(super) fn filter_delta_set<L: Deref>(delta_set: &mut DeltaSet, logger: L) where L::Target: Logger {
374 let original_length = delta_set.len();
375 let keys: Vec<u64> = delta_set.keys().cloned().collect();
377 let v = delta_set.get(&k).unwrap();
378 if v.announcement.is_none() {
379 // this channel is not currently in the network graph
380 delta_set.remove(&k);
384 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
385 if update.is_none() {
388 let update_reference = update.as_ref().unwrap();
389 // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
390 // if there has been an update after the channel was first seen
392 v.requires_reminder || update_reference.latest_update_after_seen.is_some()
395 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
396 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
398 if !v.requires_reminder && !direction_a_meets_criteria && !direction_b_meets_criteria {
399 delta_set.remove(&k);
403 let new_length = delta_set.len();
404 if original_length != new_length {
405 log_info!(logger, "length modified!");