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