ChannelManager+Router++ Logger Arc --> Deref
[rust-lightning] / lightning / src / routing / router.rs
1 //! The top-level routing/network map tracking logic lives here.
2 //!
3 //! You probably want to create a NetGraphMsgHandler and use that as your RoutingMessageHandler and then
4 //! interrogate it to get routes for your own payments.
5
6 use bitcoin::secp256k1::key::PublicKey;
7
8 use chain::chaininterface::ChainWatchInterface;
9 use ln::channelmanager;
10 use ln::features::{ChannelFeatures, NodeFeatures};
11 use ln::msgs::{DecodeError,ErrorAction,LightningError};
12 use routing::network_graph::{NetGraphMsgHandler, RoutingFees};
13 use util::ser::{Writeable, Readable};
14 use util::logger::Logger;
15
16 use std::cmp;
17 use std::collections::{HashMap,BinaryHeap};
18 use std::ops::Deref;
19
20 /// A hop in a route
21 #[derive(Clone, PartialEq)]
22 pub struct RouteHop {
23         /// The node_id of the node at this hop.
24         pub pubkey: PublicKey,
25         /// The node_announcement features of the node at this hop. For the last hop, these may be
26         /// amended to match the features present in the invoice this node generated.
27         pub node_features: NodeFeatures,
28         /// The channel that should be used from the previous hop to reach this node.
29         pub short_channel_id: u64,
30         /// The channel_announcement features of the channel that should be used from the previous hop
31         /// to reach this node.
32         pub channel_features: ChannelFeatures,
33         /// The fee taken on this hop. For the last hop, this should be the full value of the payment.
34         pub fee_msat: u64,
35         /// The CLTV delta added for this hop. For the last hop, this should be the full CLTV value
36         /// expected at the destination, in excess of the current block height.
37         pub cltv_expiry_delta: u32,
38 }
39
40 impl Writeable for Vec<RouteHop> {
41         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
42                 (self.len() as u8).write(writer)?;
43                 for hop in self.iter() {
44                         hop.pubkey.write(writer)?;
45                         hop.node_features.write(writer)?;
46                         hop.short_channel_id.write(writer)?;
47                         hop.channel_features.write(writer)?;
48                         hop.fee_msat.write(writer)?;
49                         hop.cltv_expiry_delta.write(writer)?;
50                 }
51                 Ok(())
52         }
53 }
54
55 impl Readable for Vec<RouteHop> {
56         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Vec<RouteHop>, DecodeError> {
57                 let hops_count: u8 = Readable::read(reader)?;
58                 let mut hops = Vec::with_capacity(hops_count as usize);
59                 for _ in 0..hops_count {
60                         hops.push(RouteHop {
61                                 pubkey: Readable::read(reader)?,
62                                 node_features: Readable::read(reader)?,
63                                 short_channel_id: Readable::read(reader)?,
64                                 channel_features: Readable::read(reader)?,
65                                 fee_msat: Readable::read(reader)?,
66                                 cltv_expiry_delta: Readable::read(reader)?,
67                         });
68                 }
69                 Ok(hops)
70         }
71 }
72
73 /// A route directs a payment from the sender (us) to the recipient. If the recipient supports MPP,
74 /// it can take multiple paths. Each path is composed of one or more hops through the network.
75 #[derive(Clone, PartialEq)]
76 pub struct Route {
77         /// The list of routes taken for a single (potentially-)multi-part payment. The pubkey of the
78         /// last RouteHop in each path must be the same.
79         /// Each entry represents a list of hops, NOT INCLUDING our own, where the last hop is the
80         /// destination. Thus, this must always be at least length one. While the maximum length of any
81         /// given path is variable, keeping the length of any path to less than 20 should currently
82         /// ensure it is viable.
83         pub paths: Vec<Vec<RouteHop>>,
84 }
85
86 impl Writeable for Route {
87         fn write<W: ::util::ser::Writer>(&self, writer: &mut W) -> Result<(), ::std::io::Error> {
88                 (self.paths.len() as u64).write(writer)?;
89                 for hops in self.paths.iter() {
90                         hops.write(writer)?;
91                 }
92                 Ok(())
93         }
94 }
95
96 impl Readable for Route {
97         fn read<R: ::std::io::Read>(reader: &mut R) -> Result<Route, DecodeError> {
98                 let path_count: u64 = Readable::read(reader)?;
99                 let mut paths = Vec::with_capacity(cmp::min(path_count, 128) as usize);
100                 for _ in 0..path_count {
101                         paths.push(Readable::read(reader)?);
102                 }
103                 Ok(Route { paths })
104         }
105 }
106
107 /// A channel descriptor which provides a last-hop route to get_route
108 pub struct RouteHint {
109         /// The node_id of the non-target end of the route
110         pub src_node_id: PublicKey,
111         /// The short_channel_id of this channel
112         pub short_channel_id: u64,
113         /// The fees which must be paid to use this channel
114         pub fees: RoutingFees,
115         /// The difference in CLTV values between this node and the next node.
116         pub cltv_expiry_delta: u16,
117         /// The minimum value, in msat, which must be relayed to the next hop.
118         pub htlc_minimum_msat: u64,
119 }
120
121 #[derive(Eq, PartialEq)]
122 struct RouteGraphNode {
123         pubkey: PublicKey,
124         lowest_fee_to_peer_through_node: u64,
125         lowest_fee_to_node: u64,
126 }
127
128 impl cmp::Ord for RouteGraphNode {
129         fn cmp(&self, other: &RouteGraphNode) -> cmp::Ordering {
130                 other.lowest_fee_to_peer_through_node.cmp(&self.lowest_fee_to_peer_through_node)
131                         .then_with(|| other.pubkey.serialize().cmp(&self.pubkey.serialize()))
132         }
133 }
134
135 impl cmp::PartialOrd for RouteGraphNode {
136         fn partial_cmp(&self, other: &RouteGraphNode) -> Option<cmp::Ordering> {
137                 Some(self.cmp(other))
138         }
139 }
140
141 struct DummyDirectionalChannelInfo {
142         cltv_expiry_delta: u32,
143         htlc_minimum_msat: u64,
144         fees: RoutingFees,
145 }
146
147
148 /// Gets a route from us (as specified in the provided NetGraphMsgHandler) to the given target node.
149 ///
150 /// Extra routing hops between known nodes and the target will be used if they are included in
151 /// last_hops.
152 ///
153 /// If some channels aren't announced, it may be useful to fill in a first_hops with the
154 /// results from a local ChannelManager::list_usable_channels() call. If it is filled in, our
155 /// view of our local channels (from net_graph_msg_handler) will be ignored, and only those in first_hops
156 /// will be used.
157 ///
158 /// Panics if first_hops contains channels without short_channel_ids
159 /// (ChannelManager::list_usable_channels will never include such channels).
160 ///
161 /// The fees on channels from us to next-hops are ignored (as they are assumed to all be
162 /// equal), however the enabled/disabled bit on such channels as well as the htlc_minimum_msat
163 /// *is* checked as they may change based on the receiving node.
164 pub fn get_route<C: Deref, L: Deref>(our_node_id: &PublicKey, net_graph_msg_handler: &NetGraphMsgHandler<C, L>, target: &PublicKey, first_hops: Option<&[channelmanager::ChannelDetails]>,
165         last_hops: &[RouteHint], final_value_msat: u64, final_cltv: u32, logger: L) -> Result<Route, LightningError> where C::Target: ChainWatchInterface, L::Target: Logger {
166         // TODO: Obviously *only* using total fee cost sucks. We should consider weighting by
167         // uptime/success in using a node in the past.
168         if *target == *our_node_id {
169                 return Err(LightningError{err: "Cannot generate a route to ourselves", action: ErrorAction::IgnoreError});
170         }
171
172         if final_value_msat > 21_000_000 * 1_0000_0000 * 1000 {
173                 return Err(LightningError{err: "Cannot generate a route of more value than all existing satoshis", action: ErrorAction::IgnoreError});
174         }
175
176         // We do a dest-to-source Dijkstra's sorting by each node's distance from the destination
177         // plus the minimum per-HTLC fee to get from it to another node (aka "shitty A*").
178         // TODO: There are a few tweaks we could do, including possibly pre-calculating more stuff
179         // to use as the A* heuristic beyond just the cost to get one node further than the current
180         // one.
181
182         let dummy_directional_info = DummyDirectionalChannelInfo { // used for first_hops routes
183                 cltv_expiry_delta: 0,
184                 htlc_minimum_msat: 0,
185                 fees: RoutingFees {
186                         base_msat: 0,
187                         proportional_millionths: 0,
188                 }
189         };
190
191         let network = net_graph_msg_handler.network_graph.read().unwrap();
192         let mut targets = BinaryHeap::new(); //TODO: Do we care about switching to eg Fibbonaci heap?
193         let mut dist = HashMap::with_capacity(network.get_nodes().len());
194
195         let mut first_hop_targets = HashMap::with_capacity(if first_hops.is_some() { first_hops.as_ref().unwrap().len() } else { 0 });
196         if let Some(hops) = first_hops {
197                 for chan in hops {
198                         let short_channel_id = chan.short_channel_id.expect("first_hops should be filled in with usable channels, not pending ones");
199                         if chan.remote_network_id == *target {
200                                 return Ok(Route {
201                                         paths: vec![vec![RouteHop {
202                                                 pubkey: chan.remote_network_id,
203                                                 node_features: chan.counterparty_features.to_context(),
204                                                 short_channel_id,
205                                                 channel_features: chan.counterparty_features.to_context(),
206                                                 fee_msat: final_value_msat,
207                                                 cltv_expiry_delta: final_cltv,
208                                         }]],
209                                 });
210                         }
211                         first_hop_targets.insert(chan.remote_network_id, (short_channel_id, chan.counterparty_features.clone()));
212                 }
213                 if first_hop_targets.is_empty() {
214                         return Err(LightningError{err: "Cannot route when there are no outbound routes away from us", action: ErrorAction::IgnoreError});
215                 }
216         }
217
218         macro_rules! add_entry {
219                 // Adds entry which goes from $src_node_id to $dest_node_id
220                 // over the channel with id $chan_id with fees described in
221                 // $directional_info.
222                 ( $chan_id: expr, $src_node_id: expr, $dest_node_id: expr, $directional_info: expr, $chan_features: expr, $starting_fee_msat: expr ) => {
223                         //TODO: Explore simply adding fee to hit htlc_minimum_msat
224                         if $starting_fee_msat as u64 + final_value_msat >= $directional_info.htlc_minimum_msat {
225                                 let proportional_fee_millions = ($starting_fee_msat + final_value_msat).checked_mul($directional_info.fees.proportional_millionths as u64);
226                                 if let Some(new_fee) = proportional_fee_millions.and_then(|part| {
227                                                 ($directional_info.fees.base_msat as u64).checked_add(part / 1000000) })
228                                 {
229                                         let mut total_fee = $starting_fee_msat as u64;
230                                         let hm_entry = dist.entry(&$src_node_id);
231                                         let old_entry = hm_entry.or_insert_with(|| {
232                                                 let node = network.get_nodes().get(&$src_node_id).unwrap();
233                                                 let mut fee_base_msat = u32::max_value();
234                                                 let mut fee_proportional_millionths = u32::max_value();
235                                                 if let Some(fees) = node.lowest_inbound_channel_fees {
236                                                         fee_base_msat = fees.base_msat;
237                                                         fee_proportional_millionths = fees.proportional_millionths;
238                                                 };
239                                                 (u64::max_value(),
240                                                         fee_base_msat,
241                                                         fee_proportional_millionths,
242                                                         RouteHop {
243                                                                 pubkey: $dest_node_id.clone(),
244                                                                 node_features: NodeFeatures::empty(),
245                                                                 short_channel_id: 0,
246                                                                 channel_features: $chan_features.clone(),
247                                                                 fee_msat: 0,
248                                                                 cltv_expiry_delta: 0,
249                                                 })
250                                         });
251                                         if $src_node_id != *our_node_id {
252                                                 // Ignore new_fee for channel-from-us as we assume all channels-from-us
253                                                 // will have the same effective-fee
254                                                 total_fee += new_fee;
255                                                 if let Some(fee_inc) = final_value_msat.checked_add(total_fee).and_then(|inc| { (old_entry.2 as u64).checked_mul(inc) }) {
256                                                         total_fee += fee_inc / 1000000 + (old_entry.1 as u64);
257                                                 } else {
258                                                         // max_value means we'll always fail the old_entry.0 > total_fee check
259                                                         total_fee = u64::max_value();
260                                                 }
261                                         }
262                                         let new_graph_node = RouteGraphNode {
263                                                 pubkey: $src_node_id,
264                                                 lowest_fee_to_peer_through_node: total_fee,
265                                                 lowest_fee_to_node: $starting_fee_msat as u64 + new_fee,
266                                         };
267                                         if old_entry.0 > total_fee {
268                                                 targets.push(new_graph_node);
269                                                 old_entry.0 = total_fee;
270                                                 old_entry.3 = RouteHop {
271                                                         pubkey: $dest_node_id.clone(),
272                                                         node_features: NodeFeatures::empty(),
273                                                         short_channel_id: $chan_id.clone(),
274                                                         channel_features: $chan_features.clone(),
275                                                         fee_msat: new_fee, // This field is ignored on the last-hop anyway
276                                                         cltv_expiry_delta: $directional_info.cltv_expiry_delta as u32,
277                                                 }
278                                         }
279                                 }
280                         }
281                 };
282         }
283
284         macro_rules! add_entries_to_cheapest_to_target_node {
285                 ( $node: expr, $node_id: expr, $fee_to_target_msat: expr ) => {
286                         if first_hops.is_some() {
287                                 if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&$node_id) {
288                                         add_entry!(first_hop, *our_node_id, $node_id, dummy_directional_info, features.to_context(), $fee_to_target_msat);
289                                 }
290                         }
291
292                         let features;
293                         if let Some(node_info) = $node.announcement_info.as_ref() {
294                                 features = node_info.features.clone();
295                         } else {
296                                 features = NodeFeatures::empty();
297                         }
298
299                         if !features.requires_unknown_bits() {
300                                 for chan_id in $node.channels.iter() {
301                                         let chan = network.get_channels().get(chan_id).unwrap();
302                                         if !chan.features.requires_unknown_bits() {
303                                                 if chan.node_one == *$node_id {
304                                                         // ie $node is one, ie next hop in A* is two, via the two_to_one channel
305                                                         if first_hops.is_none() || chan.node_two != *our_node_id {
306                                                                 if let Some(two_to_one) = chan.two_to_one.as_ref() {
307                                                                         if two_to_one.enabled {
308                                                                                 add_entry!(chan_id, chan.node_two, chan.node_one, two_to_one, chan.features, $fee_to_target_msat);
309                                                                         }
310                                                                 }
311                                                         }
312                                                 } else {
313                                                         if first_hops.is_none() || chan.node_one != *our_node_id {
314                                                                 if let Some(one_to_two) = chan.one_to_two.as_ref() {
315                                                                         if one_to_two.enabled {
316                                                                                 add_entry!(chan_id, chan.node_one, chan.node_two, one_to_two, chan.features, $fee_to_target_msat);
317                                                                         }
318                                                                 }
319
320                                                         }
321                                                 }
322                                         }
323                                 }
324                         }
325                 };
326         }
327
328         match network.get_nodes().get(target) {
329                 None => {},
330                 Some(node) => {
331                         add_entries_to_cheapest_to_target_node!(node, target, 0);
332                 },
333         }
334
335         for hop in last_hops.iter() {
336                 if first_hops.is_none() || hop.src_node_id != *our_node_id { // first_hop overrules last_hops
337                         if network.get_nodes().get(&hop.src_node_id).is_some() {
338                                 if first_hops.is_some() {
339                                         if let Some(&(ref first_hop, ref features)) = first_hop_targets.get(&hop.src_node_id) {
340                                                 // Currently there are no channel-context features defined, so we are a
341                                                 // bit lazy here. In the future, we should pull them out via our
342                                                 // ChannelManager, but there's no reason to waste the space until we
343                                                 // need them.
344                                                 add_entry!(first_hop, *our_node_id , hop.src_node_id, dummy_directional_info, features.to_context(), 0);
345                                         }
346                                 }
347                                 // BOLT 11 doesn't allow inclusion of features for the last hop hints, which
348                                 // really sucks, cause we're gonna need that eventually.
349                                 add_entry!(hop.short_channel_id, hop.src_node_id, target, hop, ChannelFeatures::empty(), 0);
350                         }
351                 }
352         }
353
354         while let Some(RouteGraphNode { pubkey, lowest_fee_to_node, .. }) = targets.pop() {
355                 if pubkey == *our_node_id {
356                         let mut res = vec!(dist.remove(&our_node_id).unwrap().3);
357                         loop {
358                                 if let Some(&(_, ref features)) = first_hop_targets.get(&res.last().unwrap().pubkey) {
359                                         res.last_mut().unwrap().node_features = features.to_context();
360                                 } else if let Some(node) = network.get_nodes().get(&res.last().unwrap().pubkey) {
361                                         if let Some(node_info) = node.announcement_info.as_ref() {
362                                                 res.last_mut().unwrap().node_features = node_info.features.clone();
363                                         } else {
364                                                 res.last_mut().unwrap().node_features = NodeFeatures::empty();
365                                         }
366                                 } else {
367                                         // We should be able to fill in features for everything except the last
368                                         // hop, if the last hop was provided via a BOLT 11 invoice (though we
369                                         // should be able to extend it further as BOLT 11 does have feature
370                                         // flags for the last hop node itself).
371                                         assert!(res.last().unwrap().pubkey == *target);
372                                 }
373                                 if res.last().unwrap().pubkey == *target {
374                                         break;
375                                 }
376
377                                 let new_entry = match dist.remove(&res.last().unwrap().pubkey) {
378                                         Some(hop) => hop.3,
379                                         None => return Err(LightningError{err: "Failed to find a non-fee-overflowing path to the given destination", action: ErrorAction::IgnoreError}),
380                                 };
381                                 res.last_mut().unwrap().fee_msat = new_entry.fee_msat;
382                                 res.last_mut().unwrap().cltv_expiry_delta = new_entry.cltv_expiry_delta;
383                                 res.push(new_entry);
384                         }
385                         res.last_mut().unwrap().fee_msat = final_value_msat;
386                         res.last_mut().unwrap().cltv_expiry_delta = final_cltv;
387                         let route = Route { paths: vec![res] };
388                         log_trace!(logger, "Got route: {}", log_route!(route));
389                         return Ok(route);
390                 }
391
392                 match network.get_nodes().get(&pubkey) {
393                         None => {},
394                         Some(node) => {
395                                 add_entries_to_cheapest_to_target_node!(node, &pubkey, lowest_fee_to_node);
396                         },
397                 }
398         }
399
400         Err(LightningError{err: "Failed to find a path to the given destination", action: ErrorAction::IgnoreError})
401 }
402
403 #[cfg(test)]
404 mod tests {
405         use chain::chaininterface;
406         use routing::router::{NetGraphMsgHandler, RoutingFees};
407         use routing::router::{get_route, RouteHint};
408         use ln::features::{ChannelFeatures, InitFeatures, NodeFeatures};
409         use ln::msgs::{ErrorAction, LightningError, UnsignedChannelAnnouncement, ChannelAnnouncement, RoutingMessageHandler,
410            NodeAnnouncement, UnsignedNodeAnnouncement, ChannelUpdate, UnsignedChannelUpdate};
411         use ln::channelmanager;
412         use util::test_utils;
413         use util::ser::Writeable;
414
415         use bitcoin::hashes::sha256d::Hash as Sha256dHash;
416         use bitcoin::hashes::Hash;
417         use bitcoin::network::constants::Network;
418         use bitcoin::blockdata::constants::genesis_block;
419         use bitcoin::util::hash::BitcoinHash;
420
421         use hex;
422
423         use bitcoin::secp256k1::key::{PublicKey,SecretKey};
424         use bitcoin::secp256k1::{Secp256k1, All};
425
426         use std::sync::Arc;
427
428         // Using the same keys for LN and BTC ids
429         fn add_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_1_privkey: &SecretKey,
430            node_2_privkey: &SecretKey, features: ChannelFeatures, short_channel_id: u64) {
431                 let node_id_1 = PublicKey::from_secret_key(&secp_ctx, node_1_privkey);
432                 let node_id_2 = PublicKey::from_secret_key(&secp_ctx, node_2_privkey);
433
434                 let unsigned_announcement = UnsignedChannelAnnouncement {
435                         features,
436                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
437                         short_channel_id,
438                         node_id_1,
439                         node_id_2,
440                         bitcoin_key_1: node_id_1,
441                         bitcoin_key_2: node_id_2,
442                         excess_data: Vec::new(),
443                 };
444
445                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
446                 let valid_announcement = ChannelAnnouncement {
447                         node_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
448                         node_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
449                         bitcoin_signature_1: secp_ctx.sign(&msghash, node_1_privkey),
450                         bitcoin_signature_2: secp_ctx.sign(&msghash, node_2_privkey),
451                         contents: unsigned_announcement.clone(),
452                 };
453                 match net_graph_msg_handler.handle_channel_announcement(&valid_announcement) {
454                         Ok(res) => assert!(res),
455                         _ => panic!()
456                 };
457         }
458
459         fn update_channel(net_graph_msg_handler: &NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey, update: UnsignedChannelUpdate) {
460                 let msghash = hash_to_message!(&Sha256dHash::hash(&update.encode()[..])[..]);
461                 let valid_channel_update = ChannelUpdate {
462                         signature: secp_ctx.sign(&msghash, node_privkey),
463                         contents: update.clone()
464                 };
465
466                 match net_graph_msg_handler.handle_channel_update(&valid_channel_update) {
467                         Ok(res) => assert!(res),
468                         // Err(_) => panic!()
469                         Err(e) => println!("{:?}", e.err)
470                 };
471         }
472
473
474         fn add_or_update_node(net_graph_msg_handler: &NetGraphMsgHandler<Arc<chaininterface::ChainWatchInterfaceUtil>, Arc<test_utils::TestLogger>>, secp_ctx: &Secp256k1<All>, node_privkey: &SecretKey,
475            features: NodeFeatures, timestamp: u32) {
476                 let node_id = PublicKey::from_secret_key(&secp_ctx, node_privkey);
477                 let unsigned_announcement = UnsignedNodeAnnouncement {
478                         features,
479                         timestamp,
480                         node_id,
481                         rgb: [0; 3],
482                         alias: [0; 32],
483                         addresses: Vec::new(),
484                         excess_address_data: Vec::new(),
485                         excess_data: Vec::new(),
486                 };
487                 let msghash = hash_to_message!(&Sha256dHash::hash(&unsigned_announcement.encode()[..])[..]);
488                 let valid_announcement = NodeAnnouncement {
489                         signature: secp_ctx.sign(&msghash, node_privkey),
490                         contents: unsigned_announcement.clone()
491                 };
492
493                 match net_graph_msg_handler.handle_node_announcement(&valid_announcement) {
494                         Ok(_) => (),
495                         Err(_) => panic!()
496                 };
497         }
498
499         #[test]
500         fn route_test() {
501                 let secp_ctx = Secp256k1::new();
502                 let our_privkey = &SecretKey::from_slice(&hex::decode("0101010101010101010101010101010101010101010101010101010101010101").unwrap()[..]).unwrap();
503                 let our_id = PublicKey::from_secret_key(&secp_ctx, our_privkey);
504                 let logger = Arc::new(test_utils::TestLogger::new());
505                 let chain_monitor = Arc::new(chaininterface::ChainWatchInterfaceUtil::new(Network::Testnet));
506                 let net_graph_msg_handler = NetGraphMsgHandler::new(chain_monitor, Arc::clone(&logger));
507                 // Build network from our_id to node8:
508                 //
509                 //        -1(1)2-  node1  -1(3)2-
510                 //       /                       \
511                 // our_id -1(12)2- node8 -1(13)2--- node3
512                 //       \                       /
513                 //        -1(2)2-  node2  -1(4)2-
514                 //
515                 //
516                 // chan1  1-to-2: disabled
517                 // chan1  2-to-1: enabled, 0 fee
518                 //
519                 // chan2  1-to-2: enabled, ignored fee
520                 // chan2  2-to-1: enabled, 0 fee
521                 //
522                 // chan3  1-to-2: enabled, 0 fee
523                 // chan3  2-to-1: enabled, 100 msat fee
524                 //
525                 // chan4  1-to-2: enabled, 100% fee
526                 // chan4  2-to-1: enabled, 0 fee
527                 //
528                 // chan12 1-to-2: enabled, ignored fee
529                 // chan12 2-to-1: enabled, 0 fee
530                 //
531                 // chan13 1-to-2: enabled, 200% fee
532                 // chan13 2-to-1: enabled, 0 fee
533                 //
534                 //
535                 //       -1(5)2- node4 -1(8)2--
536                 //       |         2          |
537                 //       |       (11)         |
538                 //      /          1           \
539                 // node3--1(6)2- node5 -1(9)2--- node7 (not in global route map)
540                 //      \                      /
541                 //       -1(7)2- node6 -1(10)2-
542                 //
543                 // chan5  1-to-2: enabled, 100 msat fee
544                 // chan5  2-to-1: enabled, 0 fee
545                 //
546                 // chan6  1-to-2: enabled, 0 fee
547                 // chan6  2-to-1: enabled, 0 fee
548                 //
549                 // chan7  1-to-2: enabled, 100% fee
550                 // chan7  2-to-1: enabled, 0 fee
551                 //
552                 // chan8  1-to-2: enabled, variable fee (0 then 1000 msat)
553                 // chan8  2-to-1: enabled, 0 fee
554                 //
555                 // chan9  1-to-2: enabled, 1001 msat fee
556                 // chan9  2-to-1: enabled, 0 fee
557                 //
558                 // chan10 1-to-2: enabled, 0 fee
559                 // chan10 2-to-1: enabled, 0 fee
560                 //
561                 // chan11 1-to-2: enabled, 0 fee
562                 // chan11 2-to-1: enabled, 0 fee
563
564                 let node1_privkey = &SecretKey::from_slice(&hex::decode("0202020202020202020202020202020202020202020202020202020202020202").unwrap()[..]).unwrap();
565                 let node2_privkey = &SecretKey::from_slice(&hex::decode("0303030303030303030303030303030303030303030303030303030303030303").unwrap()[..]).unwrap();
566                 let node3_privkey = &SecretKey::from_slice(&hex::decode("0404040404040404040404040404040404040404040404040404040404040404").unwrap()[..]).unwrap();
567                 let node4_privkey = &SecretKey::from_slice(&hex::decode("0505050505050505050505050505050505050505050505050505050505050505").unwrap()[..]).unwrap();
568                 let node5_privkey = &SecretKey::from_slice(&hex::decode("0606060606060606060606060606060606060606060606060606060606060606").unwrap()[..]).unwrap();
569                 let node6_privkey = &SecretKey::from_slice(&hex::decode("0707070707070707070707070707070707070707070707070707070707070707").unwrap()[..]).unwrap();
570                 let node7_privkey = &SecretKey::from_slice(&hex::decode("0808080808080808080808080808080808080808080808080808080808080808").unwrap()[..]).unwrap();
571                 let node8_privkey = &SecretKey::from_slice(&hex::decode("0909090909090909090909090909090909090909090909090909090909090909").unwrap()[..]).unwrap();
572
573
574                 let node1 = PublicKey::from_secret_key(&secp_ctx, node1_privkey);
575                 let node2 = PublicKey::from_secret_key(&secp_ctx, node2_privkey);
576                 let node3 = PublicKey::from_secret_key(&secp_ctx, node3_privkey);
577                 let node4 = PublicKey::from_secret_key(&secp_ctx, node4_privkey);
578                 let node5 = PublicKey::from_secret_key(&secp_ctx, node5_privkey);
579                 let node6 = PublicKey::from_secret_key(&secp_ctx, node6_privkey);
580                 let node7 = PublicKey::from_secret_key(&secp_ctx, node7_privkey);
581                 let node8 = PublicKey::from_secret_key(&secp_ctx, node8_privkey);
582
583                 macro_rules! id_to_feature_flags {
584                         // Set the feature flags to the id'th odd (ie non-required) feature bit so that we can
585                         // test for it later.
586                         ($id: expr) => { {
587                                 let idx = ($id - 1) * 2 + 1;
588                                 if idx > 8*3 {
589                                         vec![1 << (idx - 8*3), 0, 0, 0]
590                                 } else if idx > 8*2 {
591                                         vec![1 << (idx - 8*2), 0, 0]
592                                 } else if idx > 8*1 {
593                                         vec![1 << (idx - 8*1), 0]
594                                 } else {
595                                         vec![1 << idx]
596                                 }
597                         } }
598                 }
599
600                 add_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, node1_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(1)), 1);
601                 update_channel(&net_graph_msg_handler, &secp_ctx, node1_privkey, UnsignedChannelUpdate {
602                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
603                         short_channel_id: 1,
604                         timestamp: 1,
605                         flags: 1,
606                         cltv_expiry_delta: 0,
607                         htlc_minimum_msat: 0,
608                         fee_base_msat: 0,
609                         fee_proportional_millionths: 0,
610                         excess_data: Vec::new()
611                 });
612                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node1_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(1)), 0);
613
614                 add_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, node2_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(2)), 2);
615                 update_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, UnsignedChannelUpdate {
616                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
617                         short_channel_id: 2,
618                         timestamp: 1,
619                         flags: 0,
620                         cltv_expiry_delta: u16::max_value(),
621                         htlc_minimum_msat: 0,
622                         fee_base_msat: u32::max_value(),
623                         fee_proportional_millionths: u32::max_value(),
624                         excess_data: Vec::new()
625                 });
626                 update_channel(&net_graph_msg_handler, &secp_ctx, node2_privkey, UnsignedChannelUpdate {
627                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
628                         short_channel_id: 2,
629                         timestamp: 1,
630                         flags: 1,
631                         cltv_expiry_delta: 0,
632                         htlc_minimum_msat: 0,
633                         fee_base_msat: 0,
634                         fee_proportional_millionths: 0,
635                         excess_data: Vec::new()
636                 });
637
638                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node2_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(2)), 0);
639
640                 add_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, node8_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(12)), 12);
641                 update_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, UnsignedChannelUpdate {
642                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
643                         short_channel_id: 12,
644                         timestamp: 1,
645                         flags: 0,
646                         cltv_expiry_delta: u16::max_value(),
647                         htlc_minimum_msat: 0,
648                         fee_base_msat: u32::max_value(),
649                         fee_proportional_millionths: u32::max_value(),
650                         excess_data: Vec::new()
651                 });
652                 update_channel(&net_graph_msg_handler, &secp_ctx, node8_privkey, UnsignedChannelUpdate {
653                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
654                         short_channel_id: 12,
655                         timestamp: 1,
656                         flags: 1,
657                         cltv_expiry_delta: 0,
658                         htlc_minimum_msat: 0,
659                         fee_base_msat: 0,
660                         fee_proportional_millionths: 0,
661                         excess_data: Vec::new()
662                 });
663
664
665                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node8_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(8)), 0);
666
667                 add_channel(&net_graph_msg_handler, &secp_ctx, node1_privkey, node3_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(3)), 3);
668                 update_channel(&net_graph_msg_handler, &secp_ctx, node1_privkey, UnsignedChannelUpdate {
669                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
670                         short_channel_id: 3,
671                         timestamp: 1,
672                         flags: 0,
673                         cltv_expiry_delta: (3 << 8) | 1,
674                         htlc_minimum_msat: 0,
675                         fee_base_msat: 0,
676                         fee_proportional_millionths: 0,
677                         excess_data: Vec::new()
678                 });
679                 update_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, UnsignedChannelUpdate {
680                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
681                         short_channel_id: 3,
682                         timestamp: 1,
683                         flags: 1,
684                         cltv_expiry_delta: (3 << 8) | 2,
685                         htlc_minimum_msat: 0,
686                         fee_base_msat: 100,
687                         fee_proportional_millionths: 0,
688                         excess_data: Vec::new()
689                 });
690
691
692                 add_channel(&net_graph_msg_handler, &secp_ctx, node2_privkey, node3_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(4)), 4);
693                 update_channel(&net_graph_msg_handler, &secp_ctx, node2_privkey, UnsignedChannelUpdate {
694                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
695                         short_channel_id: 4,
696                         timestamp: 1,
697                         flags: 0,
698                         cltv_expiry_delta: (4 << 8) | 1,
699                         htlc_minimum_msat: 0,
700                         fee_base_msat: 0,
701                         fee_proportional_millionths: 1000000,
702                         excess_data: Vec::new()
703                 });
704                 update_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, UnsignedChannelUpdate {
705                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
706                         short_channel_id: 4,
707                         timestamp: 1,
708                         flags: 1,
709                         cltv_expiry_delta: (4 << 8) | 2,
710                         htlc_minimum_msat: 0,
711                         fee_base_msat: 0,
712                         fee_proportional_millionths: 0,
713                         excess_data: Vec::new()
714                 });
715
716                 add_channel(&net_graph_msg_handler, &secp_ctx, node8_privkey, node3_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(13)), 13);
717                 update_channel(&net_graph_msg_handler, &secp_ctx, node8_privkey, UnsignedChannelUpdate {
718                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
719                         short_channel_id: 13,
720                         timestamp: 1,
721                         flags: 0,
722                         cltv_expiry_delta: (13 << 8) | 1,
723                         htlc_minimum_msat: 0,
724                         fee_base_msat: 0,
725                         fee_proportional_millionths: 2000000,
726                         excess_data: Vec::new()
727                 });
728                 update_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, UnsignedChannelUpdate {
729                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
730                         short_channel_id: 13,
731                         timestamp: 1,
732                         flags: 1,
733                         cltv_expiry_delta: (13 << 8) | 2,
734                         htlc_minimum_msat: 0,
735                         fee_base_msat: 0,
736                         fee_proportional_millionths: 0,
737                         excess_data: Vec::new()
738                 });
739                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node3_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(3)), 0);
740                 add_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, node5_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(6)), 6);
741
742                 update_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, UnsignedChannelUpdate {
743                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
744                         short_channel_id: 6,
745                         timestamp: 1,
746                         flags: 0,
747                         cltv_expiry_delta: (6 << 8) | 1,
748                         htlc_minimum_msat: 0,
749                         fee_base_msat: 0,
750                         fee_proportional_millionths: 0,
751                         excess_data: Vec::new()
752                 });
753                 update_channel(&net_graph_msg_handler, &secp_ctx, node5_privkey, UnsignedChannelUpdate {
754                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
755                         short_channel_id: 6,
756                         timestamp: 1,
757                         flags: 1,
758                         cltv_expiry_delta: (6 << 8) | 2,
759                         htlc_minimum_msat: 0,
760                         fee_base_msat: 0,
761                         fee_proportional_millionths: 0,
762                         excess_data: Vec::new()
763                 });
764
765                 add_channel(&net_graph_msg_handler, &secp_ctx, node5_privkey, node4_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(11)), 11);
766                 update_channel(&net_graph_msg_handler, &secp_ctx, node5_privkey, UnsignedChannelUpdate {
767                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
768                         short_channel_id: 11,
769                         timestamp: 1,
770                         flags: 0,
771                         cltv_expiry_delta: (11 << 8) | 1,
772                         htlc_minimum_msat: 0,
773                         fee_base_msat: 0,
774                         fee_proportional_millionths: 0,
775                         excess_data: Vec::new()
776                 });
777                 update_channel(&net_graph_msg_handler, &secp_ctx, node4_privkey, UnsignedChannelUpdate {
778                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
779                         short_channel_id: 11,
780                         timestamp: 1,
781                         flags: 1,
782                         cltv_expiry_delta: (11 << 8) | 2,
783                         htlc_minimum_msat: 0,
784                         fee_base_msat: 0,
785                         fee_proportional_millionths: 0,
786                         excess_data: Vec::new()
787                 });
788                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node5_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(5)), 0);
789                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node4_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(4)), 0);
790
791                 add_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, node6_privkey, ChannelFeatures::from_le_bytes(id_to_feature_flags!(7)), 7);
792
793                 update_channel(&net_graph_msg_handler, &secp_ctx, node3_privkey, UnsignedChannelUpdate {
794                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
795                         short_channel_id: 7,
796                         timestamp: 1,
797                         flags: 0,
798                         cltv_expiry_delta: (7 << 8) | 1,
799                         htlc_minimum_msat: 0,
800                         fee_base_msat: 0,
801                         fee_proportional_millionths: 1000000,
802                         excess_data: Vec::new()
803                 });
804                 update_channel(&net_graph_msg_handler, &secp_ctx, node6_privkey, UnsignedChannelUpdate {
805                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
806                         short_channel_id: 7,
807                         timestamp: 1,
808                         flags: 1,
809                         cltv_expiry_delta: (7 << 8) | 2,
810                         htlc_minimum_msat: 0,
811                         fee_base_msat: 0,
812                         fee_proportional_millionths: 0,
813                         excess_data: Vec::new()
814                 });
815
816                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node6_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(6)), 0);
817
818                 // Simple route to 3 via 2
819                 let route = get_route(&our_id, &net_graph_msg_handler, &node3, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
820                 assert_eq!(route.paths[0].len(), 2);
821
822                 assert_eq!(route.paths[0][0].pubkey, node2);
823                 assert_eq!(route.paths[0][0].short_channel_id, 2);
824                 assert_eq!(route.paths[0][0].fee_msat, 100);
825                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
826                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
827                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
828
829                 assert_eq!(route.paths[0][1].pubkey, node3);
830                 assert_eq!(route.paths[0][1].short_channel_id, 4);
831                 assert_eq!(route.paths[0][1].fee_msat, 100);
832                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
833                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
834                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
835
836
837                 // // Disable channels 4 and 12 by flags=2
838                 update_channel(&net_graph_msg_handler, &secp_ctx, node2_privkey, UnsignedChannelUpdate {
839                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
840                         short_channel_id: 4,
841                         timestamp: 2,
842                         flags: 2, // to disable
843                         cltv_expiry_delta: 0,
844                         htlc_minimum_msat: 0,
845                         fee_base_msat: 0,
846                         fee_proportional_millionths: 0,
847                         excess_data: Vec::new()
848                 });
849                 update_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, UnsignedChannelUpdate {
850                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
851                         short_channel_id: 12,
852                         timestamp: 2,
853                         flags: 2, // to disable
854                         cltv_expiry_delta: 0,
855                         htlc_minimum_msat: 0,
856                         fee_base_msat: 0,
857                         fee_proportional_millionths: 0,
858                         excess_data: Vec::new()
859                 });
860
861                 // If all the channels require some features we don't understand, route should fail
862                 if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler, &node3, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
863                         assert_eq!(err, "Failed to find a path to the given destination");
864                 } else { panic!(); }
865
866                 // If we specify a channel to node8, that overrides our local channel view and that gets used
867                 let our_chans = vec![channelmanager::ChannelDetails {
868                         channel_id: [0; 32],
869                         short_channel_id: Some(42),
870                         remote_network_id: node8.clone(),
871                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
872                         channel_value_satoshis: 0,
873                         user_id: 0,
874                         outbound_capacity_msat: 0,
875                         inbound_capacity_msat: 0,
876                         is_live: true,
877                 }];
878                 let route = get_route(&our_id, &net_graph_msg_handler, &node3, Some(&our_chans),  &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
879                 assert_eq!(route.paths[0].len(), 2);
880
881                 assert_eq!(route.paths[0][0].pubkey, node8);
882                 assert_eq!(route.paths[0][0].short_channel_id, 42);
883                 assert_eq!(route.paths[0][0].fee_msat, 200);
884                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
885                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
886                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
887
888                 assert_eq!(route.paths[0][1].pubkey, node3);
889                 assert_eq!(route.paths[0][1].short_channel_id, 13);
890                 assert_eq!(route.paths[0][1].fee_msat, 100);
891                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
892                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
893                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
894
895                 // Re-enable channels 4 and 12
896                 update_channel(&net_graph_msg_handler, &secp_ctx, node2_privkey, UnsignedChannelUpdate {
897                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
898                         short_channel_id: 4,
899                         timestamp: 3,
900                         flags: 0, // to enable
901                         cltv_expiry_delta: (4 << 8) | 1,
902                         htlc_minimum_msat: 0,
903                         fee_base_msat: 0,
904                         fee_proportional_millionths: 1000000,
905                         excess_data: Vec::new()
906                 });
907                 update_channel(&net_graph_msg_handler, &secp_ctx, our_privkey, UnsignedChannelUpdate {
908                         chain_hash: genesis_block(Network::Testnet).header.bitcoin_hash(),
909                         short_channel_id: 12,
910                         timestamp: 3,
911                         flags: 0, // to enable
912                         cltv_expiry_delta: u16::max_value(),
913                         htlc_minimum_msat: 0,
914                         fee_base_msat: u32::max_value(),
915                         fee_proportional_millionths: u32::max_value(),
916                         excess_data: Vec::new()
917                 });
918                 // Disable nodes 1, 2, and 8 by requiring unknown feature bits
919                 let mut unknown_features = NodeFeatures::known();
920                 unknown_features.set_required_unknown_bits();
921                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node1_privkey, unknown_features.clone(), 1);
922                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node2_privkey, unknown_features.clone(), 1);
923                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node8_privkey, unknown_features.clone(), 1);
924
925                 // // If all nodes require some features we don't understand, route should fail
926                 // if let Err(LightningError{err, action: ErrorAction::IgnoreError}) = get_route(&our_id, &net_graph_msg_handler, &node3, None, &Vec::new(), 100, 42, Arc::clone(&logger)) {
927                 //      assert_eq!(err, "Failed to find a path to the given destination");
928                 // } else { panic!(); }
929
930                 // If we specify a channel to node8, that overrides our local channel view and that gets used
931                 let our_chans = vec![channelmanager::ChannelDetails {
932                         channel_id: [0; 32],
933                         short_channel_id: Some(42),
934                         remote_network_id: node8.clone(),
935                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
936                         channel_value_satoshis: 0,
937                         user_id: 0,
938                         outbound_capacity_msat: 0,
939                         inbound_capacity_msat: 0,
940                         is_live: true,
941                 }];
942                 let route = get_route(&our_id, &net_graph_msg_handler, &node3, Some(&our_chans), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
943                 assert_eq!(route.paths[0].len(), 2);
944
945                 assert_eq!(route.paths[0][0].pubkey, node8);
946                 assert_eq!(route.paths[0][0].short_channel_id, 42);
947                 assert_eq!(route.paths[0][0].fee_msat, 200);
948                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
949                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]); // it should also override our view of their features
950                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
951
952                 assert_eq!(route.paths[0][1].pubkey, node3);
953                 assert_eq!(route.paths[0][1].short_channel_id, 13);
954                 assert_eq!(route.paths[0][1].fee_msat, 100);
955                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
956                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
957                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
958
959                 // Re-enable nodes 1, 2, and 8
960                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node1_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(1)), 2);
961                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node2_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(2)), 2);
962                 add_or_update_node(&net_graph_msg_handler, &secp_ctx, node8_privkey, NodeFeatures::from_le_bytes(id_to_feature_flags!(8)), 2);
963
964                 // Note that we don't test disabling node 3 and failing to route to it, as we (somewhat
965                 // naively) assume that the user checked the feature bits on the invoice, which override
966                 // the node_announcement.
967
968                 // Route to 1 via 2 and 3 because our channel to 1 is disabled
969                 let route = get_route(&our_id, &net_graph_msg_handler, &node1, None, &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
970                 assert_eq!(route.paths[0].len(), 3);
971
972                 assert_eq!(route.paths[0][0].pubkey, node2);
973                 assert_eq!(route.paths[0][0].short_channel_id, 2);
974                 assert_eq!(route.paths[0][0].fee_msat, 200);
975                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
976                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
977                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
978
979                 assert_eq!(route.paths[0][1].pubkey, node3);
980                 assert_eq!(route.paths[0][1].short_channel_id, 4);
981                 assert_eq!(route.paths[0][1].fee_msat, 100);
982                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (3 << 8) | 2);
983                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
984                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
985
986                 assert_eq!(route.paths[0][2].pubkey, node1);
987                 assert_eq!(route.paths[0][2].short_channel_id, 3);
988                 assert_eq!(route.paths[0][2].fee_msat, 100);
989                 assert_eq!(route.paths[0][2].cltv_expiry_delta, 42);
990                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(1));
991                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(3));
992
993                 // If we specify a channel to node8, that overrides our local channel view and that gets used
994                 let our_chans = vec![channelmanager::ChannelDetails {
995                         channel_id: [0; 32],
996                         short_channel_id: Some(42),
997                         remote_network_id: node8.clone(),
998                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
999                         channel_value_satoshis: 0,
1000                         user_id: 0,
1001                         outbound_capacity_msat: 0,
1002                         inbound_capacity_msat: 0,
1003                         is_live: true,
1004                 }];
1005                 let route = get_route(&our_id, &net_graph_msg_handler, &node3, Some(&our_chans), &Vec::new(), 100, 42, Arc::clone(&logger)).unwrap();
1006                 assert_eq!(route.paths[0].len(), 2);
1007
1008                 assert_eq!(route.paths[0][0].pubkey, node8);
1009                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1010                 assert_eq!(route.paths[0][0].fee_msat, 200);
1011                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (13 << 8) | 1);
1012                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1013                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1014
1015                 assert_eq!(route.paths[0][1].pubkey, node3);
1016                 assert_eq!(route.paths[0][1].short_channel_id, 13);
1017                 assert_eq!(route.paths[0][1].fee_msat, 100);
1018                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1019                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1020                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(13));
1021
1022                 let zero_fees = RoutingFees {
1023                         base_msat: 0,
1024                         proportional_millionths: 0,
1025                 };
1026                 let mut last_hops = vec!(RouteHint {
1027                                 src_node_id: node4.clone(),
1028                                 short_channel_id: 8,
1029                                 fees: zero_fees,
1030                                 cltv_expiry_delta: (8 << 8) | 1,
1031                                 htlc_minimum_msat: 0,
1032                         }, RouteHint {
1033                                 src_node_id: node5.clone(),
1034                                 short_channel_id: 9,
1035                                 fees: RoutingFees {
1036                                         base_msat: 1001,
1037                                         proportional_millionths: 0,
1038                                 },
1039                                 cltv_expiry_delta: (9 << 8) | 1,
1040                                 htlc_minimum_msat: 0,
1041                         }, RouteHint {
1042                                 src_node_id: node6.clone(),
1043                                 short_channel_id: 10,
1044                                 fees: zero_fees,
1045                                 cltv_expiry_delta: (10 << 8) | 1,
1046                                 htlc_minimum_msat: 0,
1047                         });
1048
1049                 // Simple test across 2, 3, 5, and 4 via a last_hop channel
1050                 let route = get_route(&our_id, &net_graph_msg_handler, &node7, None, &last_hops, 100, 42, Arc::clone(&logger)).unwrap();
1051                 assert_eq!(route.paths[0].len(), 5);
1052
1053                 assert_eq!(route.paths[0][0].pubkey, node2);
1054                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1055                 assert_eq!(route.paths[0][0].fee_msat, 100);
1056                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1057                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1058                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1059
1060                 assert_eq!(route.paths[0][1].pubkey, node3);
1061                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1062                 assert_eq!(route.paths[0][1].fee_msat, 0);
1063                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1064                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1065                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1066
1067                 assert_eq!(route.paths[0][2].pubkey, node5);
1068                 assert_eq!(route.paths[0][2].short_channel_id, 6);
1069                 assert_eq!(route.paths[0][2].fee_msat, 0);
1070                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1071                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1072                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1073
1074                 assert_eq!(route.paths[0][3].pubkey, node4);
1075                 assert_eq!(route.paths[0][3].short_channel_id, 11);
1076                 assert_eq!(route.paths[0][3].fee_msat, 0);
1077                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1078                 // If we have a peer in the node map, we'll use their features here since we don't have
1079                 // a way of figuring out their features from the invoice:
1080                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1081                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1082
1083                 assert_eq!(route.paths[0][4].pubkey, node7);
1084                 assert_eq!(route.paths[0][4].short_channel_id, 8);
1085                 assert_eq!(route.paths[0][4].fee_msat, 100);
1086                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1087                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1088                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1089
1090                 // Simple test with outbound channel to 4 to test that last_hops and first_hops connect
1091                 let our_chans = vec![channelmanager::ChannelDetails {
1092                         channel_id: [0; 32],
1093                         short_channel_id: Some(42),
1094                         remote_network_id: node4.clone(),
1095                         counterparty_features: InitFeatures::from_le_bytes(vec![0b11]),
1096                         channel_value_satoshis: 0,
1097                         user_id: 0,
1098                         outbound_capacity_msat: 0,
1099                         inbound_capacity_msat: 0,
1100                         is_live: true,
1101                 }];
1102                 let route = get_route(&our_id, &net_graph_msg_handler, &node7, Some(&our_chans), &last_hops, 100, 42, Arc::clone(&logger)).unwrap();
1103                 assert_eq!(route.paths[0].len(), 2);
1104
1105                 assert_eq!(route.paths[0][0].pubkey, node4);
1106                 assert_eq!(route.paths[0][0].short_channel_id, 42);
1107                 assert_eq!(route.paths[0][0].fee_msat, 0);
1108                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (8 << 8) | 1);
1109                 assert_eq!(route.paths[0][0].node_features.le_flags(), &vec![0b11]);
1110                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &Vec::new()); // No feature flags will meet the relevant-to-channel conversion
1111
1112                 assert_eq!(route.paths[0][1].pubkey, node7);
1113                 assert_eq!(route.paths[0][1].short_channel_id, 8);
1114                 assert_eq!(route.paths[0][1].fee_msat, 100);
1115                 assert_eq!(route.paths[0][1].cltv_expiry_delta, 42);
1116                 assert_eq!(route.paths[0][1].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1117                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1118
1119                 last_hops[0].fees.base_msat = 1000;
1120
1121                 // Revert to via 6 as the fee on 8 goes up
1122                 let route = get_route(&our_id, &net_graph_msg_handler, &node7, None, &last_hops, 100, 42, Arc::clone(&logger)).unwrap();
1123                 assert_eq!(route.paths[0].len(), 4);
1124
1125                 assert_eq!(route.paths[0][0].pubkey, node2);
1126                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1127                 assert_eq!(route.paths[0][0].fee_msat, 200); // fee increased as its % of value transferred across node
1128                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1129                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1130                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1131
1132                 assert_eq!(route.paths[0][1].pubkey, node3);
1133                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1134                 assert_eq!(route.paths[0][1].fee_msat, 100);
1135                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (7 << 8) | 1);
1136                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1137                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1138
1139                 assert_eq!(route.paths[0][2].pubkey, node6);
1140                 assert_eq!(route.paths[0][2].short_channel_id, 7);
1141                 assert_eq!(route.paths[0][2].fee_msat, 0);
1142                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (10 << 8) | 1);
1143                 // If we have a peer in the node map, we'll use their features here since we don't have
1144                 // a way of figuring out their features from the invoice:
1145                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(6));
1146                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(7));
1147
1148                 assert_eq!(route.paths[0][3].pubkey, node7);
1149                 assert_eq!(route.paths[0][3].short_channel_id, 10);
1150                 assert_eq!(route.paths[0][3].fee_msat, 100);
1151                 assert_eq!(route.paths[0][3].cltv_expiry_delta, 42);
1152                 assert_eq!(route.paths[0][3].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1153                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1154
1155                 // ...but still use 8 for larger payments as 6 has a variable feerate
1156                 let route = get_route(&our_id, &net_graph_msg_handler, &node7, None, &last_hops, 2000, 42, Arc::clone(&logger)).unwrap();
1157                 assert_eq!(route.paths[0].len(), 5);
1158
1159                 assert_eq!(route.paths[0][0].pubkey, node2);
1160                 assert_eq!(route.paths[0][0].short_channel_id, 2);
1161                 assert_eq!(route.paths[0][0].fee_msat, 3000);
1162                 assert_eq!(route.paths[0][0].cltv_expiry_delta, (4 << 8) | 1);
1163                 assert_eq!(route.paths[0][0].node_features.le_flags(), &id_to_feature_flags!(2));
1164                 assert_eq!(route.paths[0][0].channel_features.le_flags(), &id_to_feature_flags!(2));
1165
1166                 assert_eq!(route.paths[0][1].pubkey, node3);
1167                 assert_eq!(route.paths[0][1].short_channel_id, 4);
1168                 assert_eq!(route.paths[0][1].fee_msat, 0);
1169                 assert_eq!(route.paths[0][1].cltv_expiry_delta, (6 << 8) | 1);
1170                 assert_eq!(route.paths[0][1].node_features.le_flags(), &id_to_feature_flags!(3));
1171                 assert_eq!(route.paths[0][1].channel_features.le_flags(), &id_to_feature_flags!(4));
1172
1173                 assert_eq!(route.paths[0][2].pubkey, node5);
1174                 assert_eq!(route.paths[0][2].short_channel_id, 6);
1175                 assert_eq!(route.paths[0][2].fee_msat, 0);
1176                 assert_eq!(route.paths[0][2].cltv_expiry_delta, (11 << 8) | 1);
1177                 assert_eq!(route.paths[0][2].node_features.le_flags(), &id_to_feature_flags!(5));
1178                 assert_eq!(route.paths[0][2].channel_features.le_flags(), &id_to_feature_flags!(6));
1179
1180                 assert_eq!(route.paths[0][3].pubkey, node4);
1181                 assert_eq!(route.paths[0][3].short_channel_id, 11);
1182                 assert_eq!(route.paths[0][3].fee_msat, 1000);
1183                 assert_eq!(route.paths[0][3].cltv_expiry_delta, (8 << 8) | 1);
1184                 // If we have a peer in the node map, we'll use their features here since we don't have
1185                 // a way of figuring out their features from the invoice:
1186                 assert_eq!(route.paths[0][3].node_features.le_flags(), &id_to_feature_flags!(4));
1187                 assert_eq!(route.paths[0][3].channel_features.le_flags(), &id_to_feature_flags!(11));
1188
1189                 assert_eq!(route.paths[0][4].pubkey, node7);
1190                 assert_eq!(route.paths[0][4].short_channel_id, 8);
1191                 assert_eq!(route.paths[0][4].fee_msat, 2000);
1192                 assert_eq!(route.paths[0][4].cltv_expiry_delta, 42);
1193                 assert_eq!(route.paths[0][4].node_features.le_flags(), &Vec::new()); // We dont pass flags in from invoices yet
1194                 assert_eq!(route.paths[0][4].channel_features.le_flags(), &Vec::new()); // We can't learn any flags from invoices, sadly
1195         }
1196 }