696b4d041ab508b53c7074884a63b89047d4957a
[rapid-gossip-sync-server] / src / lookup.rs
1 use std::collections::{BTreeMap, HashSet};
2 use std::io::Cursor;
3 use std::ops::Deref;
4 use std::sync::Arc;
5 use std::time::{Instant, SystemTime, UNIX_EPOCH};
6
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;
11
12 use futures::StreamExt;
13 use lightning::log_info;
14 use lightning::util::logger::Logger;
15
16 use crate::config;
17 use crate::serialization::MutatedProperties;
18
19 /// The delta set needs to be a BTreeMap so the keys are sorted.
20 /// That way, the scids in the response automatically grow monotonically
21 pub(super) type DeltaSet = BTreeMap<u64, ChannelDelta>;
22
23 pub(super) struct AnnouncementDelta {
24         pub(super) seen: u32,
25         pub(super) announcement: UnsignedChannelAnnouncement,
26 }
27
28 pub(super) struct UpdateDelta {
29         pub(super) seen: u32,
30         pub(super) update: UnsignedChannelUpdate,
31 }
32
33 pub(super) struct DirectedUpdateDelta {
34         pub(super) last_update_before_seen: Option<UnsignedChannelUpdate>,
35         pub(super) mutated_properties: MutatedProperties,
36         pub(super) latest_update_after_seen: Option<UpdateDelta>,
37         pub(super) serialization_update_flags: Option<u8>,
38 }
39
40 pub(super) struct ChannelDelta {
41         pub(super) announcement: Option<AnnouncementDelta>,
42         pub(super) updates: (Option<DirectedUpdateDelta>, Option<DirectedUpdateDelta>),
43         pub(super) first_bidirectional_updates_seen: Option<u32>,
44         /// The seen timestamp of the older of the two latest directional updates
45         pub(super) requires_reminder: bool,
46 }
47
48 impl Default for ChannelDelta {
49         fn default() -> Self {
50                 Self {
51                         announcement: None,
52                         updates: (None, None),
53                         first_bidirectional_updates_seen: None,
54                         requires_reminder: false,
55                 }
56         }
57 }
58
59 impl Default for DirectedUpdateDelta {
60         fn default() -> Self {
61                 Self {
62                         last_update_before_seen: None,
63                         mutated_properties: MutatedProperties::default(),
64                         latest_update_after_seen: None,
65                         serialization_update_flags: None,
66                 }
67         }
68 }
69
70 /// Fetch all the channel announcements that are presently in the network graph, regardless of
71 /// whether they had been seen before.
72 /// Also include all announcements for which the first update was announced
73 /// after `last_sync_timestamp`
74 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 {
75         log_info!(logger, "Obtaining channel ids from network graph");
76         let channel_ids = {
77                 let read_only_graph = network_graph.read_only();
78                 log_info!(logger, "Retrieved read-only network graph copy");
79                 let channel_iterator = read_only_graph.channels().unordered_iter();
80                 channel_iterator
81                         .filter(|c| c.1.announcement_message.is_some())
82                         .map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
83                         .collect::<Vec<_>>()
84         };
85         #[cfg(test)]
86         log_info!(logger, "Channel IDs: {:?}", channel_ids);
87         log_info!(logger, "Last sync timestamp: {}", last_sync_timestamp);
88         let last_sync_timestamp_float = last_sync_timestamp as f64;
89
90         log_info!(logger, "Obtaining corresponding database entries");
91         // get all the channel announcements that are currently in the network graph
92         let announcement_rows = client.query_raw("SELECT announcement_signed, CAST(EXTRACT('epoch' from seen) AS BIGINT) AS seen FROM channel_announcements WHERE short_channel_id = any($1) ORDER BY short_channel_id ASC", [&channel_ids]).await.unwrap();
93         let mut pinned_rows = Box::pin(announcement_rows);
94
95         let mut announcement_count = 0;
96         while let Some(row_res) = pinned_rows.next().await {
97                 let current_announcement_row = row_res.unwrap();
98                 let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
99                 let mut readable = Cursor::new(blob);
100                 let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
101
102                 let scid = unsigned_announcement.short_channel_id;
103                 let current_seen_timestamp = current_announcement_row.get::<_, i64>("seen") as u32;
104
105                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
106                 (*current_channel_delta).announcement = Some(AnnouncementDelta {
107                         announcement: unsigned_announcement,
108                         seen: current_seen_timestamp,
109                 });
110
111                 announcement_count += 1;
112         }
113         log_info!(logger, "Fetched {} announcement rows", announcement_count);
114
115         {
116                 // THIS STEP IS USED TO DETERMINE IF A CHANNEL SHOULD BE OMITTED FROM THE DELTA
117
118                 log_info!(logger, "Annotating channel announcements whose oldest channel update in a given direction occurred after the last sync");
119                 // Steps:
120                 // — Obtain all updates, distinct by (scid, direction), ordered by seen DESC // to find the oldest update in a given direction
121                 // — From those updates, select distinct by (scid), ordered by seen DESC (to obtain the newer one per direction)
122                 // This will allow us to mark the first time updates in both directions were seen
123
124                 // here is where the channels whose first update in either direction occurred after
125                 // `last_seen_timestamp` are added to the selection
126                 let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
127                         [&channel_ids, &last_sync_timestamp_float];
128                 let newer_oldest_directional_updates = client.query_raw("
129                         SELECT short_channel_id, CAST(EXTRACT('epoch' from distinct_chans.seen) AS BIGINT) AS seen FROM (
130                                 SELECT DISTINCT ON (short_channel_id) *
131                                 FROM (
132                                         SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
133                                         FROM channel_updates
134                                         WHERE short_channel_id = any($1)
135                                         ORDER BY short_channel_id ASC, direction ASC, seen ASC
136                                 ) AS directional_last_seens
137                                 ORDER BY short_channel_id ASC, seen DESC
138                         ) AS distinct_chans
139                         WHERE distinct_chans.seen >= TO_TIMESTAMP($2)
140                         ", params).await.unwrap();
141                 let mut pinned_updates = Box::pin(newer_oldest_directional_updates);
142
143                 let mut newer_oldest_directional_update_count = 0;
144                 while let Some(row_res) = pinned_updates.next().await {
145                         let current_row = row_res.unwrap();
146
147                         let scid: i64 = current_row.get("short_channel_id");
148                         let current_seen_timestamp = current_row.get::<_, i64>("seen") as u32;
149
150                         // the newer of the two oldest seen directional updates came after last sync timestamp
151                         let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
152                         // first time a channel was seen in both directions
153                         (*current_channel_delta).first_bidirectional_updates_seen = Some(current_seen_timestamp);
154
155                         newer_oldest_directional_update_count += 1;
156                 }
157                 log_info!(logger, "Fetched {} update rows of the first update in a new direction", newer_oldest_directional_update_count);
158         }
159
160         {
161                 // THIS STEP IS USED TO DETERMINE IF A REMINDER UPDATE SHOULD BE SENT
162
163                 log_info!(logger, "Annotating channel announcements whose latest channel update in a given direction occurred more than six days ago");
164                 // Steps:
165                 // — Obtain all updates, distinct by (scid, direction), ordered by seen DESC
166                 // — From those updates, select distinct by (scid), ordered by seen ASC (to obtain the older one per direction)
167                 let reminder_threshold_timestamp = SystemTime::now().checked_sub(config::CHANNEL_REMINDER_AGE).unwrap().duration_since(UNIX_EPOCH).unwrap().as_secs() as f64;
168
169                 let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
170                         [&channel_ids, &reminder_threshold_timestamp];
171                 let older_latest_directional_updates = client.query_raw("
172                         SELECT short_channel_id FROM (
173                                 SELECT DISTINCT ON (short_channel_id) *
174                                 FROM (
175                                         SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
176                                         FROM channel_updates
177                                         WHERE short_channel_id = any($1)
178                                         ORDER BY short_channel_id ASC, direction ASC, seen DESC
179                                 ) AS directional_last_seens
180                                 ORDER BY short_channel_id ASC, seen ASC
181                         ) AS distinct_chans
182                         WHERE distinct_chans.seen <= TO_TIMESTAMP($2)
183                         ", params).await.unwrap();
184                 let mut pinned_updates = Box::pin(older_latest_directional_updates);
185
186                 let mut older_latest_directional_update_count = 0;
187                 while let Some(row_res) = pinned_updates.next().await {
188                         let current_row = row_res.unwrap();
189                         let scid: i64 = current_row.get("short_channel_id");
190
191                         // annotate this channel as requiring that reminders be sent to the client
192                         let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
193
194                         // way might be able to get away with not using this
195                         (*current_channel_delta).requires_reminder = true;
196
197                         if let Some(current_channel_info) = network_graph.read_only().channel(scid as u64) {
198                                 if current_channel_info.one_to_two.is_none() || current_channel_info.two_to_one.is_none() {
199                                         // we don't send reminders if we don't have bidirectional update data
200                                         continue;
201                                 }
202
203                                 if let Some(info) = current_channel_info.one_to_two.as_ref() {
204                                         let flags: u8 = if info.enabled { 0 } else { 2 };
205                                         let current_update = (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default());
206                                         current_update.serialization_update_flags = Some(flags);
207                                 }
208
209                                 if let Some(info) = current_channel_info.two_to_one.as_ref() {
210                                         let flags: u8 = if info.enabled { 1 } else { 3 };
211                                         let current_update = (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default());
212                                         current_update.serialization_update_flags = Some(flags);
213                                 }
214                         } else {
215                                 // we don't send reminders if we don't have the channel
216                                 continue;
217                         }
218                         older_latest_directional_update_count += 1;
219                 }
220                 log_info!(logger, "Fetched {} update rows of the latest update in the less recently updated direction", older_latest_directional_update_count);
221         }
222 }
223
224 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 {
225         let start = Instant::now();
226         let last_sync_timestamp_float = last_sync_timestamp as f64;
227
228         // get the latest channel update in each direction prior to last_sync_timestamp, provided
229         // there was an update in either direction that happened after the last sync (to avoid
230         // collecting too many reference updates)
231         let reference_rows = client.query_raw("
232                 SELECT id, direction, blob_signed FROM channel_updates
233                 WHERE id IN (
234                         SELECT DISTINCT ON (short_channel_id, direction) id
235                         FROM channel_updates
236                         WHERE seen < TO_TIMESTAMP($1) AND short_channel_id IN (
237                                 SELECT DISTINCT ON (short_channel_id) short_channel_id
238                                 FROM channel_updates
239                                 WHERE seen >= TO_TIMESTAMP($1)
240                         )
241                         ORDER BY short_channel_id ASC, direction ASC, seen DESC
242                 )
243                 ", [last_sync_timestamp_float]).await.unwrap();
244         let mut pinned_rows = Box::pin(reference_rows);
245
246         log_info!(logger, "Fetched reference rows in {:?}", start.elapsed());
247
248         let mut last_seen_update_ids: Vec<i32> = Vec::new();
249         let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
250         let mut reference_row_count = 0;
251
252         while let Some(row_res) = pinned_rows.next().await {
253                 let current_reference = row_res.unwrap();
254                 let update_id: i32 = current_reference.get("id");
255                 last_seen_update_ids.push(update_id);
256                 non_intermediate_ids.insert(update_id);
257
258                 let direction: bool = current_reference.get("direction");
259                 let blob: Vec<u8> = current_reference.get("blob_signed");
260                 let mut readable = Cursor::new(blob);
261                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
262                 let scid = unsigned_channel_update.short_channel_id;
263
264                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
265                 let update_delta = if !direction {
266                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
267                 } else {
268                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
269                 };
270                 update_delta.last_update_before_seen = Some(unsigned_channel_update);
271                 reference_row_count += 1;
272         }
273
274         log_info!(logger, "Processed {} reference rows (delta size: {}) in {:?}",
275                 reference_row_count, delta_set.len(), start.elapsed());
276
277         // get all the intermediate channel updates
278         // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
279         // have been omitted)
280
281         let intermediate_updates = client.query_raw("
282                 SELECT id, direction, blob_signed, CAST(EXTRACT('epoch' from seen) AS BIGINT) AS seen
283                 FROM channel_updates
284                 WHERE seen >= TO_TIMESTAMP($1)
285                 ORDER BY timestamp DESC
286                 ", [last_sync_timestamp_float]).await.unwrap();
287         let mut pinned_updates = Box::pin(intermediate_updates);
288         log_info!(logger, "Fetched intermediate rows in {:?}", start.elapsed());
289
290         let mut previous_scid = u64::MAX;
291         let mut previously_seen_directions = (false, false);
292
293         // let mut previously_seen_directions = (false, false);
294         let mut intermediate_update_count = 0;
295         while let Some(row_res) = pinned_updates.next().await {
296                 let intermediate_update = row_res.unwrap();
297                 let update_id: i32 = intermediate_update.get("id");
298                 if non_intermediate_ids.contains(&update_id) {
299                         continue;
300                 }
301                 intermediate_update_count += 1;
302
303                 let direction: bool = intermediate_update.get("direction");
304                 let current_seen_timestamp = intermediate_update.get::<_, i64>("seen") as u32;
305                 let blob: Vec<u8> = intermediate_update.get("blob_signed");
306                 let mut readable = Cursor::new(blob);
307                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
308
309                 let scid = unsigned_channel_update.short_channel_id;
310                 if scid != previous_scid {
311                         previous_scid = scid;
312                         previously_seen_directions = (false, false);
313                 }
314
315                 // get the write configuration for this particular channel's directional details
316                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
317                 let update_delta = if !direction {
318                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
319                 } else {
320                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
321                 };
322
323                 {
324                         // handle the latest deltas
325                         if !direction && !previously_seen_directions.0 {
326                                 previously_seen_directions.0 = true;
327                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
328                                         seen: current_seen_timestamp,
329                                         update: unsigned_channel_update.clone(),
330                                 });
331                         } else if direction && !previously_seen_directions.1 {
332                                 previously_seen_directions.1 = true;
333                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
334                                         seen: current_seen_timestamp,
335                                         update: unsigned_channel_update.clone(),
336                                 });
337                         }
338                 }
339
340                 // determine mutations
341                 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref() {
342                         if unsigned_channel_update.flags != last_seen_update.flags {
343                                 update_delta.mutated_properties.flags = true;
344                         }
345                         if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
346                                 update_delta.mutated_properties.cltv_expiry_delta = true;
347                         }
348                         if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
349                                 update_delta.mutated_properties.htlc_minimum_msat = true;
350                         }
351                         if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
352                                 update_delta.mutated_properties.fee_base_msat = true;
353                         }
354                         if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
355                                 update_delta.mutated_properties.fee_proportional_millionths = true;
356                         }
357                         if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
358                                 update_delta.mutated_properties.htlc_maximum_msat = true;
359                         }
360                 }
361         }
362         log_info!(logger, "Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
363 }
364
365 pub(super) fn filter_delta_set<L: Deref>(delta_set: &mut DeltaSet, logger: L) where L::Target: Logger {
366         let original_length = delta_set.len();
367         let keys: Vec<u64> = delta_set.keys().cloned().collect();
368         for k in keys {
369                 let v = delta_set.get(&k).unwrap();
370                 if v.announcement.is_none() {
371                         // this channel is not currently in the network graph
372                         delta_set.remove(&k);
373                         continue;
374                 }
375
376                 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
377                         if update.is_none() {
378                                 return false;
379                         };
380                         let update_reference = update.as_ref().unwrap();
381                         // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
382                         // if there has been an update after the channel was first seen
383
384                         v.requires_reminder || update_reference.latest_update_after_seen.is_some()
385                 };
386
387                 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
388                 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
389
390                 if !v.requires_reminder && !direction_a_meets_criteria && !direction_b_meets_criteria {
391                         delta_set.remove(&k);
392                 }
393         }
394
395         let new_length = delta_set.len();
396         if original_length != new_length {
397                 log_info!(logger, "length modified!");
398         }
399 }