Remove println from lookup.rs
[rapid-gossip-sync-server] / src / lookup.rs
1 use std::collections::{BTreeMap, HashSet};
2 use std::io::Cursor;
3 use std::ops::{Add, Deref};
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 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 last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
83         let channel_ids = {
84                 let read_only_graph = network_graph.read_only();
85                 log_info!(logger, "Retrieved read-only network graph copy");
86                 let channel_iterator = read_only_graph.channels().unordered_iter();
87                 channel_iterator
88                         .filter(|c| c.1.announcement_message.is_some())
89                         .map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
90                         .collect::<Vec<_>>()
91         };
92
93         log_info!(logger, "Obtaining corresponding database entries");
94         // get all the channel announcements that are currently in the network graph
95         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();
96         let mut pinned_rows = Box::pin(announcement_rows);
97
98         while let Some(row_res) = pinned_rows.next().await {
99                 let current_announcement_row = row_res.unwrap();
100                 let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
101                 let mut readable = Cursor::new(blob);
102                 let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
103
104                 let scid = unsigned_announcement.short_channel_id;
105                 let current_seen_timestamp_object: SystemTime = current_announcement_row.get("seen");
106                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
107
108                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
109                 (*current_channel_delta).announcement = Some(AnnouncementDelta {
110                         announcement: unsigned_announcement,
111                         seen: current_seen_timestamp,
112                 });
113         }
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_object];
128                 let newer_oldest_directional_updates = client.query_raw("
129                         SELECT * 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 >= $2
140                         ", params).await.unwrap();
141                 let mut pinned_updates = Box::pin(newer_oldest_directional_updates);
142
143                 while let Some(row_res) = pinned_updates.next().await {
144                         let current_row = row_res.unwrap();
145
146                         let scid: i64 = current_row.get("short_channel_id");
147                         let current_seen_timestamp_object: SystemTime = current_row.get("seen");
148                         let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() 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         }
156
157         {
158                 // THIS STEP IS USED TO DETERMINE IF A REMINDER UPDATE SHOULD BE SENT
159
160                 log_info!(logger, "Annotating channel announcements whose latest channel update in a given direction occurred more than six days ago");
161                 // Steps:
162                 // — Obtain all updates, distinct by (scid, direction), ordered by seen DESC
163                 // — From those updates, select distinct by (scid), ordered by seen ASC (to obtain the older one per direction)
164                 let reminder_threshold_timestamp = SystemTime::now().checked_sub(config::CHANNEL_REMINDER_AGE).unwrap();
165
166                 let params: [&(dyn tokio_postgres::types::ToSql + Sync); 2] =
167                         [&channel_ids, &reminder_threshold_timestamp];
168                 let older_latest_directional_updates = client.query_raw("
169                         SELECT short_channel_id FROM (
170                                 SELECT DISTINCT ON (short_channel_id) *
171                                 FROM (
172                                         SELECT DISTINCT ON (short_channel_id, direction) short_channel_id, seen
173                                         FROM channel_updates
174                                         WHERE short_channel_id = any($1)
175                                         ORDER BY short_channel_id ASC, direction ASC, seen DESC
176                                 ) AS directional_last_seens
177                                 ORDER BY short_channel_id ASC, seen ASC
178                         ) AS distinct_chans
179                         WHERE distinct_chans.seen <= $2
180                         ", params).await.unwrap();
181                 let mut pinned_updates = Box::pin(older_latest_directional_updates);
182
183                 while let Some(row_res) = pinned_updates.next().await {
184                         let current_row = row_res.unwrap();
185                         let scid: i64 = current_row.get("short_channel_id");
186
187                         // annotate this channel as requiring that reminders be sent to the client
188                         let current_channel_delta = delta_set.entry(scid as u64).or_insert(ChannelDelta::default());
189
190                         // way might be able to get away with not using this
191                         (*current_channel_delta).requires_reminder = true;
192
193                         if let Some(current_channel_info) = network_graph.read_only().channel(scid as u64) {
194                                 if current_channel_info.one_to_two.is_none() || current_channel_info.two_to_one.is_none() {
195                                         // we don't send reminders if we don't have bidirectional update data
196                                         continue;
197                                 }
198
199                                 if let Some(info) = current_channel_info.one_to_two.as_ref() {
200                                         let flags: u8 = if info.enabled { 0 } else { 2 };
201                                         let current_update = (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default());
202                                         current_update.serialization_update_flags = Some(flags);
203                                 }
204
205                                 if let Some(info) = current_channel_info.two_to_one.as_ref() {
206                                         let flags: u8 = if info.enabled { 1 } else { 3 };
207                                         let current_update = (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default());
208                                         current_update.serialization_update_flags = Some(flags);
209                                 }
210                         } else {
211                                 // we don't send reminders if we don't have the channel
212                                 continue;
213                         }
214                 }
215         }
216 }
217
218 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 {
219         let start = Instant::now();
220         let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
221
222         // get the latest channel update in each direction prior to last_sync_timestamp, provided
223         // there was an update in either direction that happened after the last sync (to avoid
224         // collecting too many reference updates)
225         let reference_rows = client.query_raw("
226                 SELECT id, direction, blob_signed FROM channel_updates
227                 WHERE id IN (
228                         SELECT DISTINCT ON (short_channel_id, direction) id
229                         FROM channel_updates
230                         WHERE seen < $1 AND short_channel_id IN (
231                                 SELECT DISTINCT ON (short_channel_id) short_channel_id
232                                 FROM channel_updates
233                                 WHERE seen >= $1
234                         )
235                         ORDER BY short_channel_id ASC, direction ASC, seen DESC
236                 )
237                 ", [last_sync_timestamp_object]).await.unwrap();
238         let mut pinned_rows = Box::pin(reference_rows);
239
240         log_info!(logger, "Fetched reference rows in {:?}", start.elapsed());
241
242         let mut last_seen_update_ids: Vec<i32> = Vec::new();
243         let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
244         let mut reference_row_count = 0;
245
246         while let Some(row_res) = pinned_rows.next().await {
247                 let current_reference = row_res.unwrap();
248                 let update_id: i32 = current_reference.get("id");
249                 last_seen_update_ids.push(update_id);
250                 non_intermediate_ids.insert(update_id);
251
252                 let direction: bool = current_reference.get("direction");
253                 let blob: Vec<u8> = current_reference.get("blob_signed");
254                 let mut readable = Cursor::new(blob);
255                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
256                 let scid = unsigned_channel_update.short_channel_id;
257
258                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
259                 let update_delta = if !direction {
260                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
261                 } else {
262                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
263                 };
264                 update_delta.last_update_before_seen = Some(unsigned_channel_update);
265                 reference_row_count += 1;
266         }
267
268         log_info!(logger, "Processed {} reference rows (delta size: {}) in {:?}",
269                 reference_row_count, delta_set.len(), start.elapsed());
270
271         // get all the intermediate channel updates
272         // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
273         // have been omitted)
274
275         let intermediate_updates = client.query_raw("
276                 SELECT id, direction, blob_signed, seen
277                 FROM channel_updates
278                 WHERE seen >= $1
279                 ", [last_sync_timestamp_object]).await.unwrap();
280         let mut pinned_updates = Box::pin(intermediate_updates);
281         log_info!(logger, "Fetched intermediate rows in {:?}", start.elapsed());
282
283         let mut previous_scid = u64::MAX;
284         let mut previously_seen_directions = (false, false);
285
286         // let mut previously_seen_directions = (false, false);
287         let mut intermediate_update_count = 0;
288         while let Some(row_res) = pinned_updates.next().await {
289                 let intermediate_update = row_res.unwrap();
290                 let update_id: i32 = intermediate_update.get("id");
291                 if non_intermediate_ids.contains(&update_id) {
292                         continue;
293                 }
294                 intermediate_update_count += 1;
295
296                 let direction: bool = intermediate_update.get("direction");
297                 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
298                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
299                 let blob: Vec<u8> = intermediate_update.get("blob_signed");
300                 let mut readable = Cursor::new(blob);
301                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
302
303                 let scid = unsigned_channel_update.short_channel_id;
304                 if scid != previous_scid {
305                         previous_scid = scid;
306                         previously_seen_directions = (false, false);
307                 }
308
309                 // get the write configuration for this particular channel's directional details
310                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
311                 let update_delta = if !direction {
312                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
313                 } else {
314                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
315                 };
316
317                 {
318                         // handle the latest deltas
319                         if !direction && !previously_seen_directions.0 {
320                                 previously_seen_directions.0 = true;
321                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
322                                         seen: current_seen_timestamp,
323                                         update: unsigned_channel_update.clone(),
324                                 });
325                         } else if direction && !previously_seen_directions.1 {
326                                 previously_seen_directions.1 = true;
327                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
328                                         seen: current_seen_timestamp,
329                                         update: unsigned_channel_update.clone(),
330                                 });
331                         }
332                 }
333
334                 // determine mutations
335                 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref() {
336                         if unsigned_channel_update.flags != last_seen_update.flags {
337                                 update_delta.mutated_properties.flags = true;
338                         }
339                         if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
340                                 update_delta.mutated_properties.cltv_expiry_delta = true;
341                         }
342                         if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
343                                 update_delta.mutated_properties.htlc_minimum_msat = true;
344                         }
345                         if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
346                                 update_delta.mutated_properties.fee_base_msat = true;
347                         }
348                         if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
349                                 update_delta.mutated_properties.fee_proportional_millionths = true;
350                         }
351                         if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
352                                 update_delta.mutated_properties.htlc_maximum_msat = true;
353                         }
354                 }
355         }
356         log_info!(logger, "Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
357 }
358
359 pub(super) fn filter_delta_set<L: Deref>(delta_set: &mut DeltaSet, logger: L) where L::Target: Logger {
360         let original_length = delta_set.len();
361         let keys: Vec<u64> = delta_set.keys().cloned().collect();
362         for k in keys {
363                 let v = delta_set.get(&k).unwrap();
364                 if v.announcement.is_none() {
365                         // this channel is not currently in the network graph
366                         delta_set.remove(&k);
367                         continue;
368                 }
369
370                 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
371                         if update.is_none() {
372                                 return false;
373                         };
374                         let update_reference = update.as_ref().unwrap();
375                         // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
376                         // if there has been an update after the channel was first seen
377
378                         v.requires_reminder || update_reference.latest_update_after_seen.is_some()
379                 };
380
381                 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
382                 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
383
384                 if !v.requires_reminder && !direction_a_meets_criteria && !direction_b_meets_criteria {
385                         delta_set.remove(&k);
386                 }
387         }
388
389         let new_length = delta_set.len();
390         if original_length != new_length {
391                 log_info!(logger, "length modified!");
392         }
393 }