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