1 use std::collections::{BTreeMap, HashSet};
5 use std::time::{Duration, Instant, SystemTime};
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;
13 use crate::{config, TestLogger};
14 use crate::serialization::MutatedProperties;
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>;
20 pub(super) struct AnnouncementDelta {
22 pub(super) announcement: UnsignedChannelAnnouncement,
25 pub(super) struct UpdateDelta {
27 pub(super) update: UnsignedChannelUpdate,
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>,
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,
45 impl Default for ChannelDelta {
46 fn default() -> Self {
49 updates: (None, None),
50 first_bidirectional_updates_seen: None,
51 requires_reminder: false,
56 impl Default for DirectedUpdateDelta {
57 fn default() -> Self {
59 last_update_before_seen: None,
60 mutated_properties: MutatedProperties::default(),
61 latest_update_after_seen: None,
62 serialization_update_flags: None
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()
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");
79 let read_only_graph = network_graph.read_only();
80 println!("Retrieved read-only network graph copy");
81 let channel_iterator = read_only_graph.channels().unordered_iter();
83 .filter(|c| c.1.announcement_message.is_some())
84 .map(|c| c.1.announcement_message.as_ref().unwrap().contents.short_channel_id as i64)
88 println!("Obtaining corresponding database entries");
89 // get all the channel announcements that are currently in the network graph
90 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 for current_announcement_row in announcement_rows {
93 let blob: Vec<u8> = current_announcement_row.get("announcement_signed");
94 let mut readable = Cursor::new(blob);
95 let unsigned_announcement = ChannelAnnouncement::read(&mut readable).unwrap().contents;
97 let scid = unsigned_announcement.short_channel_id;
98 let current_seen_timestamp_object: SystemTime = current_announcement_row.get("seen");
99 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
101 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
102 (*current_channel_delta).announcement = Some(AnnouncementDelta {
103 announcement: unsigned_announcement,
104 seen: current_seen_timestamp,
108 println!("Annotating channel announcements whose oldest channel update in a given direction occurred after the last sync");
110 /// — Obtain all updates, distinct by (scid, direction), ordered by seen DESC // to find the oldest update in a given direction
111 /// — From those updates, select distinct by (scid), ordered by seen DESC (to obtain the newer one per direction)
112 /// This will allow us to mark the first time updates in both directions were seen
114 // here is where the channels whose first update in either direction occurred after
115 // `last_seen_timestamp` are added to the selection
116 let newer_oldest_directional_updates = client.query("
117 SELECT DISTINCT ON (short_channel_id) *
119 SELECT DISTINCT ON (short_channel_id, direction) blob_signed
121 WHERE short_channel_id = any($1)
122 ORDER BY seen ASC, short_channel_id ASC, direction ASC
123 ) AS directional_last_seens
124 ORDER BY short_channel_id ASC, seen DESC
125 ", &[&channel_ids]).await.unwrap();
127 for current_row in newer_oldest_directional_updates {
128 let blob: Vec<u8> = current_row.get("blob_signed");
129 let mut readable = Cursor::new(blob);
130 let unsigned_update = ChannelUpdate::read(&mut readable).unwrap().contents;
131 let scid = unsigned_update.short_channel_id;
132 let current_seen_timestamp_object: SystemTime = current_row.get("seen");
133 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
135 if current_seen_timestamp > last_sync_timestamp {
136 // the newer of the two oldest seen directional updates came after last sync timestamp
137 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
138 // first time a channel was seen in both directions
139 (*current_channel_delta).first_bidirectional_updates_seen = Some(current_seen_timestamp);
143 println!("Annotating channel announcements whose latest channel update in a given direction occurred more than six days ago");
145 /// — Obtain all updates, distinct by (scid, direction), ordered by seen DESC
146 /// — From those updates, select distinct by (scid), ordered by seen ASC (to obtain the older one per direction)
147 let current_timestamp = SystemTime::now().duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
148 let reminder_threshold_timestamp = current_timestamp.saturating_sub(config::CHANNEL_REMINDER_AGE);
149 let read_only_graph = network_graph.read_only();
151 let older_latest_directional_updates = client.query("
152 SELECT DISTINCT ON (short_channel_id) *
154 SELECT DISTINCT ON (short_channel_id, direction) *
156 WHERE short_channel_id = any($1)
157 ORDER BY short_channel_id ASC, direction ASC, seen DESC
158 ) AS directional_last_seens
159 ORDER BY short_channel_id ASC, seen ASC
160 ", &[&channel_ids]).await.unwrap();
162 for current_row in older_latest_directional_updates {
163 let blob: Vec<u8> = current_row.get("blob_signed");
164 let mut readable = Cursor::new(blob);
165 let unsigned_update = ChannelUpdate::read(&mut readable).unwrap().contents;
166 let scid = unsigned_update.short_channel_id;
167 let current_seen_timestamp_object: SystemTime = current_row.get("seen");
168 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
170 if current_seen_timestamp <= reminder_threshold_timestamp {
171 // annotate this channel as requiring that reminders be sent to the client
172 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
174 // way might be able to get away with not using this
175 (*current_channel_delta).requires_reminder = true;
177 let current_channel_info = read_only_graph.channel(scid).unwrap();
178 if let Some(info) = current_channel_info.one_to_two.as_ref() {
179 let flags: u8 = if info.enabled { 0 } else { 2 };
180 let current_update = (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default());
181 current_update.serialization_update_flags = Some(flags);
184 if let Some(info) = current_channel_info.two_to_one.as_ref() {
185 let flags: u8 = if info.enabled { 1 } else { 3 };
186 let current_update = (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default());
187 current_update.serialization_update_flags = Some(flags);
193 pub(super) async fn fetch_channel_updates(delta_set: &mut DeltaSet, client: &Client, last_sync_timestamp: u32, consider_intermediate_updates: bool) {
194 let start = Instant::now();
195 let last_sync_timestamp_object = SystemTime::UNIX_EPOCH.add(Duration::from_secs(last_sync_timestamp as u64));
197 // get the latest channel update in each direction prior to last_sync_timestamp, provided
198 // there was an update in either direction that happened after the last sync (to avoid
199 // collecting too many reference updates)
200 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();
202 println!("Fetched reference rows ({}): {:?}", reference_rows.len(), start.elapsed());
204 let mut last_seen_update_ids: Vec<i32> = Vec::with_capacity(reference_rows.len());
205 let mut non_intermediate_ids: HashSet<i32> = HashSet::new();
207 for current_reference in reference_rows {
208 let update_id: i32 = current_reference.get("id");
209 last_seen_update_ids.push(update_id);
210 non_intermediate_ids.insert(update_id);
212 let direction: bool = current_reference.get("direction");
213 let blob: Vec<u8> = current_reference.get("blob_signed");
214 let mut readable = Cursor::new(blob);
215 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
216 let scid = unsigned_channel_update.short_channel_id;
218 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
219 let update_delta = if !direction {
220 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
222 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
224 update_delta.last_update_before_seen = Some(unsigned_channel_update);
227 println!("Processed reference rows (delta size: {}): {:?}", delta_set.len(), start.elapsed());
229 // get all the intermediate channel updates
230 // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
231 // have been omitted)
233 let mut intermediate_update_prefix = "";
234 if !consider_intermediate_updates {
235 intermediate_update_prefix = "DISTINCT ON (short_channel_id, direction)";
238 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);
239 let intermediate_updates = client.query(&query_string, &[&last_sync_timestamp_object]).await.unwrap();
240 println!("Fetched intermediate rows ({}): {:?}", intermediate_updates.len(), start.elapsed());
242 let mut previous_scid = u64::MAX;
243 let mut previously_seen_directions = (false, false);
245 // let mut previously_seen_directions = (false, false);
246 let mut intermediate_update_count = 0;
247 for intermediate_update in intermediate_updates {
248 let update_id: i32 = intermediate_update.get("id");
249 if non_intermediate_ids.contains(&update_id) {
252 intermediate_update_count += 1;
254 let direction: bool = intermediate_update.get("direction");
255 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
256 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
257 let blob: Vec<u8> = intermediate_update.get("blob_signed");
258 let mut readable = Cursor::new(blob);
259 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
261 let scid = unsigned_channel_update.short_channel_id;
262 if scid != previous_scid {
263 previous_scid = scid;
264 previously_seen_directions = (false, false);
267 // get the write configuration for this particular channel's directional details
268 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
269 let update_delta = if !direction {
270 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
272 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
276 // handle the latest deltas
277 if !direction && !previously_seen_directions.0 {
278 previously_seen_directions.0 = true;
279 update_delta.latest_update_after_seen = Some(UpdateDelta {
280 seen: current_seen_timestamp,
281 update: unsigned_channel_update.clone(),
283 } else if direction && !previously_seen_directions.1 {
284 previously_seen_directions.1 = true;
285 update_delta.latest_update_after_seen = Some(UpdateDelta {
286 seen: current_seen_timestamp,
287 update: unsigned_channel_update.clone(),
292 // determine mutations
293 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref() {
294 if unsigned_channel_update.flags != last_seen_update.flags {
295 update_delta.mutated_properties.flags = true;
297 if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
298 update_delta.mutated_properties.cltv_expiry_delta = true;
300 if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
301 update_delta.mutated_properties.htlc_minimum_msat = true;
303 if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
304 update_delta.mutated_properties.fee_base_msat = true;
306 if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
307 update_delta.mutated_properties.fee_proportional_millionths = true;
309 if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
310 update_delta.mutated_properties.htlc_maximum_msat = true;
314 println!("Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
317 pub(super) fn filter_delta_set(delta_set: &mut DeltaSet) {
318 let original_length = delta_set.len();
319 let keys: Vec<u64> = delta_set.keys().cloned().collect();
321 let v = delta_set.get(&k).unwrap();
322 if v.announcement.is_none() {
323 // this channel is not currently in the network graph
324 delta_set.remove(&k);
328 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
329 if update.is_none() {
332 let update_reference = update.as_ref().unwrap();
333 // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
334 // if there has been an update after the channel was first seen
336 v.requires_reminder || update_reference.latest_update_after_seen.is_some()
339 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
340 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
342 if !v.requires_reminder && !direction_a_meets_criteria && !direction_b_meets_criteria {
343 delta_set.remove(&k);
347 let new_length = delta_set.len();
348 if original_length != new_length {
349 println!("length modified!");