Skip to content

Commit cfbd2a4

Browse files
committed
f - Move RouteHint to lightning crate
1 parent f752a48 commit cfbd2a4

File tree

6 files changed

+82
-72
lines changed

6 files changed

+82
-72
lines changed

fuzz/src/router.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ use lightning::chain::transaction::OutPoint;
1616
use lightning::ln::channelmanager::ChannelDetails;
1717
use lightning::ln::features::InitFeatures;
1818
use lightning::ln::msgs;
19-
use lightning::routing::router::{get_route, RouteHintHop};
19+
use lightning::routing::router::{get_route, RouteHint, RouteHintHop};
2020
use lightning::util::logger::Logger;
2121
use lightning::util::ser::Readable;
2222
use lightning::routing::network_graph::{NetworkGraph, RoutingFees};
@@ -225,13 +225,13 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
225225
Some(&first_hops_vec[..])
226226
},
227227
};
228-
let mut last_hops_vec = Vec::new();
228+
let mut last_hops = Vec::new();
229229
{
230230
let count = get_slice!(1)[0];
231231
for _ in 0..count {
232232
scid += 1;
233233
let rnid = node_pks.iter().skip(slice_to_be16(get_slice!(2))as usize % node_pks.len()).next().unwrap();
234-
last_hops_vec.push(RouteHintHop {
234+
last_hops.push(RouteHint(vec![RouteHintHop {
235235
src_node_id: *rnid,
236236
short_channel_id: scid,
237237
fees: RoutingFees {
@@ -241,13 +241,12 @@ pub fn do_test<Out: test_logger::Output>(data: &[u8], out: Out) {
241241
cltv_expiry_delta: slice_to_be16(get_slice!(2)),
242242
htlc_minimum_msat: Some(slice_to_be64(get_slice!(8))),
243243
htlc_maximum_msat: None,
244-
});
244+
}]));
245245
}
246246
}
247-
let last_hops = &last_hops_vec[..];
248247
for target in node_pks.iter() {
249248
let _ = get_route(&our_pubkey, &net_graph, target, None, first_hops,
250-
last_hops.iter().map(|hop| std::slice::from_ref(hop)).collect::<Vec<_>>(),
249+
last_hops.iter().collect::<Vec<_>>(),
251250
slice_to_be64(get_slice!(8)), slice_to_be32(get_slice!(4)), Arc::clone(&logger));
252251
}
253252
},

lightning-invoice/src/de.rs

+10-10
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use bitcoin_hashes::Hash;
1212
use bitcoin_hashes::sha256;
1313
use lightning::ln::PaymentSecret;
1414
use lightning::routing::network_graph::RoutingFees;
15-
use lightning::routing::router::RouteHintHop;
15+
use lightning::routing::router::{RouteHint, RouteHintHop};
1616

1717
use num_traits::{CheckedAdd, CheckedMul};
1818

@@ -21,7 +21,7 @@ use secp256k1::recovery::{RecoveryId, RecoverableSignature};
2121
use secp256k1::key::PublicKey;
2222

2323
use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiry, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
24-
SemanticError, RouteHint, Description, RawTaggedField, Currency, RawHrp, SiPrefix, RawInvoice, constants, SignedRawInvoice,
24+
SemanticError, Route, Description, RawTaggedField, Currency, RawHrp, SiPrefix, RawInvoice, constants, SignedRawInvoice,
2525
RawDataPart, CreationError, InvoiceFeatures};
2626

2727
use self::hrp_sm::parse_hrp;
@@ -434,7 +434,7 @@ impl FromBase32 for TaggedField {
434434
constants::TAG_FALLBACK =>
435435
Ok(TaggedField::Fallback(Fallback::from_base32(field_data)?)),
436436
constants::TAG_ROUTE =>
437-
Ok(TaggedField::Route(RouteHint::from_base32(field_data)?)),
437+
Ok(TaggedField::Route(Route::from_base32(field_data)?)),
438438
constants::TAG_PAYMENT_SECRET =>
439439
Ok(TaggedField::PaymentSecret(PaymentSecret::from_base32(field_data)?)),
440440
constants::TAG_FEATURES =>
@@ -558,10 +558,10 @@ impl FromBase32 for Fallback {
558558
}
559559
}
560560

561-
impl FromBase32 for RouteHint {
561+
impl FromBase32 for Route {
562562
type Err = ParseError;
563563

564-
fn from_base32(field_data: &[u5]) -> Result<RouteHint, ParseError> {
564+
fn from_base32(field_data: &[u5]) -> Result<Route, ParseError> {
565565
let bytes = Vec::<u8>::from_base32(field_data)?;
566566

567567
if bytes.len() % 51 != 0 {
@@ -593,7 +593,7 @@ impl FromBase32 for RouteHint {
593593
route_hops.push(hop);
594594
}
595595

596-
Ok(RouteHint(route_hops))
596+
Ok(Route(RouteHint(route_hops)))
597597
}
598598
}
599599

@@ -930,8 +930,8 @@ mod test {
930930
#[test]
931931
fn test_parse_route() {
932932
use lightning::routing::network_graph::RoutingFees;
933-
use lightning::routing::router::RouteHintHop;
934-
use ::RouteHint;
933+
use lightning::routing::router::{RouteHint, RouteHintHop};
934+
use ::Route;
935935
use bech32::FromBase32;
936936
use de::parse_int_be;
937937

@@ -976,10 +976,10 @@ mod test {
976976
htlc_maximum_msat: None
977977
});
978978

979-
assert_eq!(RouteHint::from_base32(&input), Ok(RouteHint(expected)));
979+
assert_eq!(Route::from_base32(&input), Ok(Route(RouteHint(expected))));
980980

981981
assert_eq!(
982-
RouteHint::from_base32(&[u5::try_from_u8(0).unwrap(); 40][..]),
982+
Route::from_base32(&[u5::try_from_u8(0).unwrap(); 40][..]),
983983
Err(ParseError::UnexpectedEndOfTaggedFields)
984984
);
985985
}

lightning-invoice/src/lib.rs

+33-26
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use lightning::ln::PaymentSecret;
3030
use lightning::ln::features::InvoiceFeatures;
3131
#[cfg(any(doc, test))]
3232
use lightning::routing::network_graph::RoutingFees;
33-
use lightning::routing::router::RouteHintHop;
33+
use lightning::routing::router::RouteHint;
3434

3535
use secp256k1::key::PublicKey;
3636
use secp256k1::{Message, Secp256k1};
@@ -362,7 +362,7 @@ pub enum TaggedField {
362362
ExpiryTime(ExpiryTime),
363363
MinFinalCltvExpiry(MinFinalCltvExpiry),
364364
Fallback(Fallback),
365-
Route(RouteHint),
365+
Route(Route),
366366
PaymentSecret(PaymentSecret),
367367
Features(InvoiceFeatures),
368368
}
@@ -419,7 +419,7 @@ pub struct InvoiceSignature(pub RecoverableSignature);
419419
/// The encoded route has to be <1024 5bit characters long (<=639 bytes or <=12 hops)
420420
///
421421
#[derive(Eq, PartialEq, Debug, Clone)]
422-
pub struct RouteHint(Vec<RouteHintHop>);
422+
pub struct Route(RouteHint);
423423

424424
/// Tag constants as specified in BOLT11
425425
#[allow(missing_docs)]
@@ -509,8 +509,8 @@ impl<D: tb::Bool, H: tb::Bool, T: tb::Bool, C: tb::Bool, S: tb::Bool> InvoiceBui
509509
}
510510

511511
/// Adds a private route.
512-
pub fn route(mut self, route: Vec<RouteHintHop>) -> Self {
513-
match RouteHint::new(route) {
512+
pub fn route(mut self, route: RouteHint) -> Self {
513+
match Route::new(route) {
514514
Ok(r) => self.tagged_fields.push(TaggedField::Route(r)),
515515
Err(e) => self.error = Some(e),
516516
}
@@ -892,11 +892,11 @@ impl RawInvoice {
892892
}).collect::<Vec<&Fallback>>()
893893
}
894894

895-
pub fn routes(&self) -> Vec<&RouteHint> {
895+
pub fn routes(&self) -> Vec<&Route> {
896896
self.known_tagged_fields().filter_map(|tf| match tf {
897897
&TaggedField::Route(ref r) => Some(r),
898898
_ => None,
899-
}).collect::<Vec<&RouteHint>>()
899+
}).collect::<Vec<&Route>>()
900900
}
901901

902902
pub fn amount_pico_btc(&self) -> Option<u64> {
@@ -1145,10 +1145,15 @@ impl Invoice {
11451145
}
11461146

11471147
/// Returns a list of all routes included in the invoice
1148-
pub fn routes(&self) -> Vec<&RouteHint> {
1148+
pub fn routes(&self) -> Vec<&Route> {
11491149
self.signed_invoice.routes()
11501150
}
11511151

1152+
/// Returns a list of all routes included in the invoice as the underlying type
1153+
pub fn route_hints(&self) -> Vec<&RouteHint> {
1154+
self.routes().into_iter().map(|route| &**route).collect()
1155+
}
1156+
11521157
/// Returns the currency for which the invoice was issued
11531158
pub fn currency(&self) -> Currency {
11541159
self.signed_invoice.currency()
@@ -1268,32 +1273,32 @@ impl ExpiryTime {
12681273
}
12691274
}
12701275

1271-
impl RouteHint {
1272-
/// Create a new (partial) route from a list of hops
1273-
pub fn new(hops: Vec<RouteHintHop>) -> Result<RouteHint, CreationError> {
1274-
if hops.len() <= 12 {
1275-
Ok(RouteHint(hops))
1276+
impl Route {
1277+
/// Creates a new (partial) route from a list of hops
1278+
pub fn new(hops: RouteHint) -> Result<Route, CreationError> {
1279+
if hops.0.len() <= 12 {
1280+
Ok(Route(hops))
12761281
} else {
12771282
Err(CreationError::RouteTooLong)
12781283
}
12791284
}
12801285

1281-
/// Returrn the underlying vector of hops
1282-
pub fn into_inner(self) -> Vec<RouteHintHop> {
1286+
/// Returns the underlying list of hops
1287+
pub fn into_inner(self) -> RouteHint {
12831288
self.0
12841289
}
12851290
}
12861291

1287-
impl Into<Vec<RouteHintHop>> for RouteHint {
1288-
fn into(self) -> Vec<RouteHintHop> {
1292+
impl Into<RouteHint> for Route {
1293+
fn into(self) -> RouteHint {
12891294
self.into_inner()
12901295
}
12911296
}
12921297

1293-
impl Deref for RouteHint {
1294-
type Target = Vec<RouteHintHop>;
1298+
impl Deref for Route {
1299+
type Target = RouteHint;
12951300

1296-
fn deref(&self) -> &Vec<RouteHintHop> {
1301+
fn deref(&self) -> &RouteHint {
12971302
&self.0
12981303
}
12991304
}
@@ -1652,6 +1657,7 @@ mod test {
16521657
#[test]
16531658
fn test_builder_fail() {
16541659
use ::*;
1660+
use lightning::routing::router::RouteHintHop;
16551661
use std::iter::FromIterator;
16561662
use secp256k1::key::PublicKey;
16571663

@@ -1686,7 +1692,7 @@ mod test {
16861692
htlc_minimum_msat: None,
16871693
htlc_maximum_msat: None,
16881694
};
1689-
let too_long_route = vec![route_hop; 13];
1695+
let too_long_route = RouteHint(vec![route_hop; 13]);
16901696
let long_route_res = builder.clone()
16911697
.description("Test".into())
16921698
.route(too_long_route)
@@ -1704,6 +1710,7 @@ mod test {
17041710
#[test]
17051711
fn test_builder_ok() {
17061712
use ::*;
1713+
use lightning::routing::router::RouteHintHop;
17071714
use secp256k1::Secp256k1;
17081715
use secp256k1::key::{SecretKey, PublicKey};
17091716
use std::time::{UNIX_EPOCH, Duration};
@@ -1719,7 +1726,7 @@ mod test {
17191726
).unwrap();
17201727
let public_key = PublicKey::from_secret_key(&secp_ctx, &private_key);
17211728

1722-
let route_1 = vec![
1729+
let route_1 = RouteHint(vec![
17231730
RouteHintHop {
17241731
src_node_id: public_key.clone(),
17251732
short_channel_id: de::parse_int_be(&[123; 8], 256).expect("short chan ID slice too big?"),
@@ -1742,9 +1749,9 @@ mod test {
17421749
htlc_minimum_msat: None,
17431750
htlc_maximum_msat: None,
17441751
}
1745-
];
1752+
]);
17461753

1747-
let route_2 = vec![
1754+
let route_2 = RouteHint(vec![
17481755
RouteHintHop {
17491756
src_node_id: public_key.clone(),
17501757
short_channel_id: 0,
@@ -1767,7 +1774,7 @@ mod test {
17671774
htlc_minimum_msat: None,
17681775
htlc_maximum_msat: None,
17691776
}
1770-
];
1777+
]);
17711778

17721779
let builder = InvoiceBuilder::new(Currency::BitcoinTestnet)
17731780
.amount_pico_btc(123)
@@ -1800,7 +1807,7 @@ mod test {
18001807
assert_eq!(invoice.expiry_time(), Duration::from_secs(54321));
18011808
assert_eq!(invoice.min_final_cltv_expiry(), 144);
18021809
assert_eq!(invoice.fallbacks(), vec![&Fallback::PubKeyHash([0;20])]);
1803-
assert_eq!(invoice.routes(), vec![&RouteHint(route_1), &RouteHint(route_2)]);
1810+
assert_eq!(invoice.routes(), vec![&Route(route_1), &Route(route_2)]);
18041811
assert_eq!(
18051812
invoice.description(),
18061813
InvoiceDescription::Hash(&Sha256(sha256::Hash::from_slice(&[3;32][..]).unwrap()))

lightning-invoice/src/ser.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ use std::fmt::{Display, Formatter};
33
use bech32::{ToBase32, u5, WriteBase32, Base32Len};
44

55
use super::{Invoice, Sha256, TaggedField, ExpiryTime, MinFinalCltvExpiry, Fallback, PayeePubKey, InvoiceSignature, PositiveTimestamp,
6-
RouteHint, Description, RawTaggedField, Currency, RawHrp, SiPrefix, constants, SignedRawInvoice, RawDataPart};
6+
Route, Description, RawTaggedField, Currency, RawHrp, SiPrefix, constants, SignedRawInvoice, RawDataPart};
77

88
/// Converts a stream of bytes written to it to base32. On finalization the according padding will
99
/// be applied. That means the results of writing two data blocks with one or two `BytesToBase32`
@@ -356,11 +356,11 @@ impl Base32Len for Fallback {
356356
}
357357
}
358358

359-
impl ToBase32 for RouteHint {
359+
impl ToBase32 for Route {
360360
fn write_base32<W: WriteBase32>(&self, writer: &mut W) -> Result<(), <W as WriteBase32>::Err> {
361361
let mut converter = BytesToBase32::new(writer);
362362

363-
for hop in self.iter() {
363+
for hop in (self.0).0.iter() {
364364
converter.append(&hop.src_node_id.serialize()[..])?;
365365
let short_channel_id = try_stretch(
366366
encode_int_be_base256(hop.short_channel_id),
@@ -392,9 +392,9 @@ impl ToBase32 for RouteHint {
392392
}
393393
}
394394

395-
impl Base32Len for RouteHint {
395+
impl Base32Len for Route {
396396
fn base32_len(&self) -> usize {
397-
bytes_size_to_base32_size(self.0.len() * 51)
397+
bytes_size_to_base32_size((self.0).0.len() * 51)
398398
}
399399
}
400400

lightning-invoice/src/utils.rs

+4-4
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use lightning::chain::chaininterface::{BroadcasterInterface, FeeEstimator};
77
use lightning::chain::keysinterface::{Sign, KeysInterface};
88
use lightning::ln::channelmanager::{ChannelManager, MIN_FINAL_CLTV_EXPIRY};
99
use lightning::routing::network_graph::RoutingFees;
10-
use lightning::routing::router::RouteHintHop;
10+
use lightning::routing::router::{RouteHint, RouteHintHop};
1111
use lightning::util::logger::Logger;
1212
use std::convert::TryInto;
1313
use std::ops::Deref;
@@ -40,7 +40,7 @@ where
4040
Some(info) => info,
4141
None => continue,
4242
};
43-
route_hints.push(vec![RouteHintHop {
43+
route_hints.push(RouteHint(vec![RouteHintHop {
4444
src_node_id: channel.remote_network_id,
4545
short_channel_id,
4646
fees: RoutingFees {
@@ -50,7 +50,7 @@ where
5050
cltv_expiry_delta: forwarding_info.cltv_expiry_delta,
5151
htlc_minimum_msat: None,
5252
htlc_maximum_msat: None,
53-
}]);
53+
}]));
5454
}
5555

5656
let (payment_hash, payment_secret) = channelmanager.create_inbound_payment(
@@ -114,7 +114,7 @@ mod test {
114114

115115
let amt_msat = invoice.amount_pico_btc().unwrap() / 10;
116116
let first_hops = nodes[0].node.list_usable_channels();
117-
let last_hops = invoice.routes().into_iter().map(|route| &(**route)[..]).collect();
117+
let last_hops = invoice.route_hints();
118118
let network_graph = nodes[0].net_graph_msg_handler.network_graph.read().unwrap();
119119
let logger = test_utils::TestLogger::new();
120120
let route = router::get_route(

0 commit comments

Comments
 (0)