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