25ea85422bf3ffdae4ee0acc7a7d07eb838269d1
[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!("Obtaining channel announcements whose first channel updates had not been seen yet");
101
102         // here is where the channels whose first update in either direction occurred after
103         // `last_seen_timestamp` are added to the selection
104         let unannounced_rows = client.query("SELECT blob_signed, seen FROM (SELECT DISTINCT ON (short_channel_id) short_channel_id, blob_signed, seen FROM channel_updates ORDER BY short_channel_id ASC, seen ASC) AS first_seens WHERE first_seens.seen >= $1", &[&last_sync_timestamp_object]).await.unwrap();
105         for current_row in unannounced_rows {
106
107                 let blob: Vec<u8> = current_row.get("blob_signed");
108                 let mut readable = Cursor::new(blob);
109                 let unsigned_update = ChannelUpdate::read(&mut readable).unwrap().contents;
110                 let scid = unsigned_update.short_channel_id;
111                 let current_seen_timestamp_object: SystemTime = current_row.get("seen");
112                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
113
114                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
115                 (*current_channel_delta).first_update_seen = Some(current_seen_timestamp);
116         }
117 }
118
119 pub(super) async fn fetch_channel_updates(delta_set: &mut DeltaSet, client: &Client, last_sync_timestamp: u32, consider_intermediate_updates: bool) {
120         let start = Instant::now();
121         let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
122
123         // get the latest channel update in each direction prior to last_sync_timestamp, provided
124         // there was an update in either direction that happened after the last sync (to avoid
125         // collecting too many reference updates)
126         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();
127
128         println!("Fetched reference rows ({}): {:?}", reference_rows.len(), start.elapsed());
129
130         let mut last_seen_update_ids: Vec<i32> = Vec::with_capacity(reference_rows.len());
131         let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
132
133         for current_reference in reference_rows {
134                 let update_id: i32 = current_reference.get("id");
135                 last_seen_update_ids.push(update_id);
136                 non_intermediate_ids.insert(update_id);
137
138                 let direction: bool = current_reference.get("direction");
139                 let blob: Vec<u8> = current_reference.get("blob_signed");
140                 let mut readable = Cursor::new(blob);
141                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
142                 let scid = unsigned_channel_update.short_channel_id;
143
144                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
145                 let update_delta = if !direction {
146                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
147                 } else {
148                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
149                 };
150                 update_delta.last_update_before_seen = Some(unsigned_channel_update);
151         }
152
153         println!("Processed reference rows (delta size: {}): {:?}", delta_set.len(), start.elapsed());
154
155         // get all the intermediate channel updates
156         // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
157         // have been omitted)
158
159         let mut intermediate_update_prefix = "";
160         if !consider_intermediate_updates {
161                 intermediate_update_prefix = "DISTINCT ON (short_channel_id, direction)";
162         }
163
164         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);
165         let intermediate_updates = client.query(&query_string, &[&last_sync_timestamp_object]).await.unwrap();
166         println!("Fetched intermediate rows ({}): {:?}", intermediate_updates.len(), start.elapsed());
167
168         let mut previous_scid = u64::MAX;
169         let mut previously_seen_directions = (false, false);
170
171         // let mut previously_seen_directions = (false, false);
172         let mut intermediate_update_count = 0;
173         for intermediate_update in intermediate_updates {
174                 let update_id: i32 = intermediate_update.get("id");
175                 if non_intermediate_ids.contains(&update_id) {
176                         continue;
177                 }
178                 intermediate_update_count += 1;
179
180                 let direction: bool = intermediate_update.get("direction");
181                 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
182                 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
183                 let blob: Vec<u8> = intermediate_update.get("blob_signed");
184                 let mut readable = Cursor::new(blob);
185                 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
186
187                 let scid = unsigned_channel_update.short_channel_id;
188                 if scid != previous_scid {
189                         previous_scid = scid;
190                         previously_seen_directions = (false, false);
191                 }
192
193                 // get the write configuration for this particular channel's directional details
194                 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
195                 let update_delta = if !direction {
196                         (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
197                 } else {
198                         (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
199                 };
200
201                 {
202                         // handle the latest deltas
203                         if !direction && !previously_seen_directions.0 {
204                                 previously_seen_directions.0 = true;
205                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
206                                         seen: current_seen_timestamp,
207                                         update: unsigned_channel_update.clone(),
208                                 });
209                         } else if direction && !previously_seen_directions.1 {
210                                 previously_seen_directions.1 = true;
211                                 update_delta.latest_update_after_seen = Some(UpdateDelta {
212                                         seen: current_seen_timestamp,
213                                         update: unsigned_channel_update.clone(),
214                                 });
215                         }
216                 }
217
218                 // determine mutations
219                 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref(){
220                         if unsigned_channel_update.flags != last_seen_update.flags {
221                                 update_delta.mutated_properties.flags = true;
222                         }
223                         if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
224                                 update_delta.mutated_properties.cltv_expiry_delta = true;
225                         }
226                         if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
227                                 update_delta.mutated_properties.htlc_minimum_msat = true;
228                         }
229                         if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
230                                 update_delta.mutated_properties.fee_base_msat = true;
231                         }
232                         if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
233                                 update_delta.mutated_properties.fee_proportional_millionths = true;
234                         }
235                         if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
236                                 update_delta.mutated_properties.htlc_maximum_msat = true;
237                         }
238                 }
239
240         }
241         println!("Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
242 }
243
244 pub(super) fn filter_delta_set(delta_set: &mut DeltaSet) {
245         let original_length = delta_set.len();
246         let keys: Vec<u64> = delta_set.keys().cloned().collect();
247         for k in keys {
248                 let v = delta_set.get(&k).unwrap();
249                 if v.announcement.is_none() {
250                         // this channel is not currently in the network graph
251                         delta_set.remove(&k);
252                         continue;
253                 }
254
255                 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
256                         if update.is_none() {
257                                 return false;
258                         };
259                         let update_reference = update.as_ref().unwrap();
260                         // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
261                         // if there has been an update after the channel was first seen
262                         update_reference.latest_update_after_seen.is_some()
263                 };
264
265                 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
266                 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
267
268                 if !direction_a_meets_criteria && !direction_b_meets_criteria {
269                         delta_set.remove(&k);
270                 }
271         }
272
273         let new_length = delta_set.len();
274         if original_length != new_length {
275                 println!("length modified!");
276         }
277 }