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