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