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