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