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>,
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>,
42 impl Default for ChannelDelta {
43 fn default() -> Self {
44 Self { announcement: None, updates: (None, None), first_update_seen: None }
48 impl Default for DirectedUpdateDelta {
49 fn default() -> Self {
51 last_update_before_seen: None,
52 mutated_properties: MutatedProperties::default(),
53 latest_update_after_seen: None,
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()
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");
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();
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)
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();
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;
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;
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,
100 println!("Annotating channel announcements whose oldest channel update in a given direction occurred after the last sync");
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
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) *
111 SELECT DISTINCT ON (short_channel_id, direction) blob_signed
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();
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;
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);
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));
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();
145 println!("Fetched reference rows ({}): {:?}", reference_rows.len(), start.elapsed());
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();
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);
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;
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())
165 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
167 update_delta.last_update_before_seen = Some(unsigned_channel_update);
170 println!("Processed reference rows (delta size: {}): {:?}", delta_set.len(), start.elapsed());
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)
176 let mut intermediate_update_prefix = "";
177 if !consider_intermediate_updates {
178 intermediate_update_prefix = "DISTINCT ON (short_channel_id, direction)";
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());
185 let mut previous_scid = u64::MAX;
186 let mut previously_seen_directions = (false, false);
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) {
195 intermediate_update_count += 1;
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;
204 let scid = unsigned_channel_update.short_channel_id;
205 if scid != previous_scid {
206 previous_scid = scid;
207 previously_seen_directions = (false, false);
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())
215 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
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(),
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(),
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;
240 if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
241 update_delta.mutated_properties.cltv_expiry_delta = true;
243 if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
244 update_delta.mutated_properties.htlc_minimum_msat = true;
246 if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
247 update_delta.mutated_properties.fee_base_msat = true;
249 if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
250 update_delta.mutated_properties.fee_proportional_millionths = true;
252 if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
253 update_delta.mutated_properties.htlc_maximum_msat = true;
258 println!("Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
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();
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);
272 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
273 if update.is_none() {
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()
282 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
283 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
285 if !direction_a_meets_criteria && !direction_b_meets_criteria {
286 delta_set.remove(&k);
290 let new_length = delta_set.len();
291 if original_length != new_length {
292 println!("length modified!");