fbd89fa41b9e838bf32e2b199970105b7b644c89
[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 }
35
36 pub(super) struct ChannelDelta {
37         pub(super) announcement: Option<AnnouncementDelta>,
38         pub(super) updates: (Option<DirectedUpdateDelta>, Option<DirectedUpdateDelta>),
39         pub(super) first_update_seen: Option<u32>,
40 }
41
42 impl Default for ChannelDelta {
43         fn default() -> Self {
44                 Self { announcement: None, updates: (None, None), first_update_seen: None }
45         }
46 }
47
48 impl Default for DirectedUpdateDelta {
49         fn default() -> Self {
50                 Self {
51                         last_update_before_seen: None,
52                         mutated_properties: MutatedProperties::default(),
53                         latest_update_after_seen: None,
54                 }
55         }
56 }
57
58 pub(super) async fn connect_to_db() -> (Client, Connection<Socket, NoTlsStream>) {
59         let connection_config = config::db_connection_config();
60         connection_config.connect(NoTls).await.unwrap()
61 }
62
63 /// Fetch all the channel announcements that are presently in the network graph, regardless of
64 /// whether they had been seen before.
65 /// Also include all announcements for which the first update was announced
66 /// after `last_syc_timestamp`
67 pub(super) async fn fetch_channel_announcements(delta_set: &mut DeltaSet, network_graph: Arc<NetworkGraph<TestLogger>>, client: &Client, last_sync_timestamp: u32) {
68         let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
69         println!("Obtaining channel ids from network graph");
70         let channel_ids = {
71                 let read_only_graph = network_graph.read_only();
72                 println!("Retrieved read-only network graph copy");
73                 let channel_iterator = read_only_graph.channels().unordered_iter();
74                 channel_iterator
75                         .filter(|c| c.1.announcement_message.is_some())
76                         .map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
77                         .collect::<Vec<_>>()
78         };
79
80         println!("Obtaining corresponding database entries");
81         // get all the channel announcements that are currently in the network graph
82         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();
83
84         for current_announcement_row in announcement_rows {
85                 let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
86                 let mut readable = Cursor::new(blob);
87                 let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
88
89                 let scid = unsigned_announcement.short_channel_id;
90                 let current_seen_timestamp_object: SystemTime = current_announcement_row.get("seen");
91                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
92
93                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
94                 (*current_channel_delta).announcement = Some(AnnouncementDelta {
95                         announcement: unsigned_announcement,
96                         seen: current_seen_timestamp,
97                 });
98         }
99
100         println!("Annotating channel announcements whose oldest channel update in a given direction occurred after the last sync");
101         /// Steps:
102         /// — Obtain all updates, distinct by (scid, direction), ordered by seen DESC // to find the oldest update in a given direction
103         /// — From those updates, select distinct by (scid), ordered by seen DESC (to obtain the newer one per direction)
104         /// This will allow us to mark the first time updates in both directions were seen
105
106         // here is where the channels whose first update in either direction occurred after
107         // `last_seen_timestamp` are added to the selection
108         let newer_oldest_directional_updates = client.query("
109                 SELECT DISTINCT ON (short_channel_id) *
110                 FROM (
111                         SELECT DISTINCT ON (short_channel_id, direction) blob_signed
112                         FROM channel_updates
113                         WHERE short_channel_id = any($1)
114                         ORDER BY seen ASC, short_channel_id ASC, direction ASC
115                 ) AS directional_last_seens
116                 ORDER BY short_channel_id ASC, seen DESC
117         ", &[&channel_ids]).await.unwrap();
118
119         for current_row in newer_oldest_directional_updates {
120                 let blob: Vec<u8> = current_row.get("blob_signed");
121                 let mut readable = Cursor::new(blob);
122                 let unsigned_update = ChannelUpdate::read(&mut readable).unwrap().contents;
123                 let scid = unsigned_update.short_channel_id;
124                 let current_seen_timestamp_object: SystemTime = current_row.get("seen");
125                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
126
127                 if (current_seen_timestamp > last_sync_timestamp) {
128                         // the newer of the two oldest seen directional updates came after last sync timestamp
129                         let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
130                         // first time a channel was seen in both directions
131                         (*current_channel_delta).first_bidirectional_updates_seen = Some(current_seen_timestamp);
132                 }
133         }
134 }
135
136 pub(super) async fn fetch_channel_updates(delta_set: &mut DeltaSet, client: &Client, last_sync_timestamp: u32, consider_intermediate_updates: bool) {
137         let start = Instant::now();
138         let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
139
140         // get the latest channel update in each direction prior to last_sync_timestamp, provided
141         // there was an update in either direction that happened after the last sync (to avoid
142         // collecting too many reference updates)
143         let reference_rows = client.query("SELECT DISTINCT ON (short_channel_id, direction) id, direction, blob_signed FROM channel_updates WHERE seen < $1 AND short_channel_id IN (SELECT short_channel_id FROM channel_updates WHERE seen >= $1 GROUP BY short_channel_id) ORDER BY short_channel_id ASC, direction ASC, seen DESC", &[&last_sync_timestamp_object]).await.unwrap();
144
145         println!("Fetched reference rows ({}): {:?}", reference_rows.len(), start.elapsed());
146
147         let mut last_seen_update_ids: Vec<i32> = Vec::with_capacity(reference_rows.len());
148         let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
149
150         for current_reference in reference_rows {
151                 let update_id: i32 = current_reference.get("id");
152                 last_seen_update_ids.push(update_id);
153                 non_intermediate_ids.insert(update_id);
154
155                 let direction: bool = current_reference.get("direction");
156                 let blob: Vec<u8> = current_reference.get("blob_signed");
157                 let mut readable = Cursor::new(blob);
158                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
159                 let scid = unsigned_channel_update.short_channel_id;
160
161                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
162                 let update_delta = if !direction {
163                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
164                 } else {
165                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
166                 };
167                 update_delta.last_update_before_seen = Some(unsigned_channel_update);
168         }
169
170         println!("Processed reference rows (delta size: {}): {:?}", delta_set.len(), start.elapsed());
171
172         // get all the intermediate channel updates
173         // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
174         // have been omitted)
175
176         let mut intermediate_update_prefix = "";
177         if !consider_intermediate_updates {
178                 intermediate_update_prefix = "DISTINCT ON (short_channel_id, direction)";
179         }
180
181         let query_string = format!("SELECT {} id, direction, blob_signed, seen FROM channel_updates WHERE seen >= $1 ORDER BY short_channel_id ASC, direction ASC, seen DESC", intermediate_update_prefix);
182         let intermediate_updates = client.query(&query_string, &[&last_sync_timestamp_object]).await.unwrap();
183         println!("Fetched intermediate rows ({}): {:?}", intermediate_updates.len(), start.elapsed());
184
185         let mut previous_scid = u64::MAX;
186         let mut previously_seen_directions = (false, false);
187
188         // let mut previously_seen_directions = (false, false);
189         let mut intermediate_update_count = 0;
190         for intermediate_update in intermediate_updates {
191                 let update_id: i32 = intermediate_update.get("id");
192                 if non_intermediate_ids.contains(&update_id) {
193                         continue;
194                 }
195                 intermediate_update_count += 1;
196
197                 let direction: bool = intermediate_update.get("direction");
198                 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
199                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
200                 let blob: Vec<u8> = intermediate_update.get("blob_signed");
201                 let mut readable = Cursor::new(blob);
202                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
203
204                 let scid = unsigned_channel_update.short_channel_id;
205                 if scid != previous_scid {
206                         previous_scid = scid;
207                         previously_seen_directions = (false, false);
208                 }
209
210                 // get the write configuration for this particular channel's directional details
211                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
212                 let update_delta = if !direction {
213                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
214                 } else {
215                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
216                 };
217
218                 {
219                         // handle the latest deltas
220                         if !direction && !previously_seen_directions.0 {
221                                 previously_seen_directions.0 = true;
222                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
223                                         seen: current_seen_timestamp,
224                                         update: unsigned_channel_update.clone(),
225                                 });
226                         } else if direction && !previously_seen_directions.1 {
227                                 previously_seen_directions.1 = true;
228                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
229                                         seen: current_seen_timestamp,
230                                         update: unsigned_channel_update.clone(),
231                                 });
232                         }
233                 }
234
235                 // determine mutations
236                 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref(){
237                         if unsigned_channel_update.flags != last_seen_update.flags {
238                                 update_delta.mutated_properties.flags = true;
239                         }
240                         if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
241                                 update_delta.mutated_properties.cltv_expiry_delta = true;
242                         }
243                         if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
244                                 update_delta.mutated_properties.htlc_minimum_msat = true;
245                         }
246                         if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
247                                 update_delta.mutated_properties.fee_base_msat = true;
248                         }
249                         if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
250                                 update_delta.mutated_properties.fee_proportional_millionths = true;
251                         }
252                         if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
253                                 update_delta.mutated_properties.htlc_maximum_msat = true;
254                         }
255                 }
256
257         }
258         println!("Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
259 }
260
261 pub(super) fn filter_delta_set(delta_set: &mut DeltaSet) {
262         let original_length = delta_set.len();
263         let keys: Vec<u64> = delta_set.keys().cloned().collect();
264         for k in keys {
265                 let v = delta_set.get(&k).unwrap();
266                 if v.announcement.is_none() {
267                         // this channel is not currently in the network graph
268                         delta_set.remove(&k);
269                         continue;
270                 }
271
272                 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
273                         if update.is_none() {
274                                 return false;
275                         };
276                         let update_reference = update.as_ref().unwrap();
277                         // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
278                         // if there has been an update after the channel was first seen
279                         update_reference.latest_update_after_seen.is_some()
280                 };
281
282                 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
283                 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
284
285                 if !direction_a_meets_criteria && !direction_b_meets_criteria {
286                         delta_set.remove(&k);
287                 }
288         }
289
290         let new_length = delta_set.len();
291         if original_length != new_length {
292                 println!("length modified!");
293         }
294 }