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, hex_utils, 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().into_iter();
75 .filter(|c| c.1.announcement_message.is_some())
76 .map(|c| hex_utils::hex_str(&c.1.announcement_message.as_ref().unwrap().contents.short_channel_id.to_be_bytes()))
77 .collect::<Vec<String>>()
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 short_channel_id, 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 mut 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!("Obtaining channel announcements whose first channel updates had not been seen yet");
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 short_channel_id, 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 {
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;
114 let mut current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
115 (*current_channel_delta).first_update_seen = Some(current_seen_timestamp);
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));
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, short_channel_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();
128 println!("Fetched reference rows ({}): {:?}", reference_rows.len(), start.elapsed());
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();
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);
138 let direction: i32 = 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;
144 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
145 let mut update_delta = if direction == 0 {
146 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
147 } else if direction == 1 {
148 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
150 panic!("Channel direction must be binary!")
152 update_delta.last_update_before_seen = Some(unsigned_channel_update);
155 println!("Processed reference rows (delta size: {}): {:?}", delta_set.len(), start.elapsed());
157 // get all the intermediate channel updates
158 // (to calculate the set of mutated fields for snapshotting, where intermediate updates may
159 // have been omitted)
161 let mut intermediate_update_prefix = "";
162 if !consider_intermediate_updates {
163 intermediate_update_prefix = "DISTINCT ON (short_channel_id, direction)";
166 let query_string = format!("SELECT {} id, short_channel_id, direction, blob_signed, seen FROM channel_updates WHERE seen >= $1 ORDER BY short_channel_id ASC, direction ASC, seen DESC", intermediate_update_prefix);
167 let intermediate_updates = client.query(&query_string, &[&last_sync_timestamp_object]).await.unwrap();
168 println!("Fetched intermediate rows ({}): {:?}", intermediate_updates.len(), start.elapsed());
170 let mut previous_scid = u64::MAX;
171 let mut previously_seen_directions = (false, false);
173 // let mut previously_seen_directions = (false, false);
174 let mut intermediate_update_count = 0;
175 for intermediate_update in intermediate_updates {
176 let update_id: i32 = intermediate_update.get("id");
177 if non_intermediate_ids.contains(&update_id) {
180 intermediate_update_count += 1;
182 let direction: i32 = intermediate_update.get("direction");
183 let current_seen_timestamp_object: SystemTime = intermediate_update.get("seen");
184 let current_seen_timestamp: u32 = current_seen_timestamp_object.duration_since(SystemTime::UNIX_EPOCH).unwrap().as_secs() as u32;
185 let blob: Vec<u8> = intermediate_update.get("blob_signed");
186 let mut readable = Cursor::new(blob);
187 let unsigned_channel_update = ChannelUpdate::read(&mut readable).unwrap().contents;
189 let scid = unsigned_channel_update.short_channel_id;
190 if scid != previous_scid {
191 previous_scid = scid;
192 previously_seen_directions = (false, false);
195 // get the write configuration for this particular channel's directional details
196 let current_channel_delta = delta_set.entry(scid).or_insert(ChannelDelta::default());
197 let update_delta = if direction == 0 {
198 (*current_channel_delta).updates.0.get_or_insert(DirectedUpdateDelta::default())
199 } else if direction == 1 {
200 (*current_channel_delta).updates.1.get_or_insert(DirectedUpdateDelta::default())
202 panic!("Channel direction must be binary!")
206 // handle the latest deltas
207 if direction == 0 && !previously_seen_directions.0 {
208 previously_seen_directions.0 = true;
209 update_delta.latest_update_after_seen = Some(UpdateDelta {
210 seen: current_seen_timestamp,
211 update: unsigned_channel_update.clone(),
213 } else if direction == 1 && !previously_seen_directions.1 {
214 previously_seen_directions.1 = true;
215 update_delta.latest_update_after_seen = Some(UpdateDelta {
216 seen: current_seen_timestamp,
217 update: unsigned_channel_update.clone(),
222 // determine mutations
223 if let Some(last_seen_update) = update_delta.last_update_before_seen.as_ref(){
224 if unsigned_channel_update.flags != last_seen_update.flags {
225 update_delta.mutated_properties.flags = true;
227 if unsigned_channel_update.cltv_expiry_delta != last_seen_update.cltv_expiry_delta {
228 update_delta.mutated_properties.cltv_expiry_delta = true;
230 if unsigned_channel_update.htlc_minimum_msat != last_seen_update.htlc_minimum_msat {
231 update_delta.mutated_properties.htlc_minimum_msat = true;
233 if unsigned_channel_update.fee_base_msat != last_seen_update.fee_base_msat {
234 update_delta.mutated_properties.fee_base_msat = true;
236 if unsigned_channel_update.fee_proportional_millionths != last_seen_update.fee_proportional_millionths {
237 update_delta.mutated_properties.fee_proportional_millionths = true;
239 if unsigned_channel_update.htlc_maximum_msat != last_seen_update.htlc_maximum_msat {
240 update_delta.mutated_properties.htlc_maximum_msat = true;
245 println!("Processed intermediate rows ({}) (delta size: {}): {:?}", intermediate_update_count, delta_set.len(), start.elapsed());
248 pub(super) fn filter_delta_set(delta_set: &mut DeltaSet) {
249 let original_length = delta_set.len();
250 let keys: Vec<u64> = delta_set.keys().cloned().collect();
252 let v = delta_set.get(&k).unwrap();
253 if v.announcement.is_none() {
254 // this channel is not currently in the network graph
255 delta_set.remove(&k);
259 let update_meets_criteria = |update: &Option<DirectedUpdateDelta>| {
260 if update.is_none() {
263 let update_reference = update.as_ref().unwrap();
264 // update_reference.latest_update_after_seen.is_some() && !update_reference.intermediate_updates.is_empty()
265 // if there has been an update after the channel was first seen
266 update_reference.latest_update_after_seen.is_some()
269 let direction_a_meets_criteria = update_meets_criteria(&v.updates.0);
270 let direction_b_meets_criteria = update_meets_criteria(&v.updates.1);
272 if !direction_a_meets_criteria && !direction_b_meets_criteria {
273 delta_set.remove(&k);
277 let new_length = delta_set.len();
278 if original_length != new_length {
279 println!("length modified!");