Skip to content

Commit 19bcb1c

Browse files
Merge pull request #2934 from TheBlueMatt/2023-03-no-num-traits
Replace the generic `parse_int_be` with a macro called twice
2 parents 5e41425 + 39c1d6b commit 19bcb1c

File tree

3 files changed

+35
-35
lines changed

3 files changed

+35
-35
lines changed

lightning-invoice/Cargo.toml

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,13 +17,12 @@ rustdoc-args = ["--cfg", "docsrs"]
1717
[features]
1818
default = ["std"]
1919
no-std = ["lightning/no-std"]
20-
std = ["bitcoin/std", "num-traits/std", "lightning/std", "bech32/std"]
20+
std = ["bitcoin/std", "lightning/std", "bech32/std"]
2121

2222
[dependencies]
2323
bech32 = { version = "0.9.0", default-features = false }
2424
lightning = { version = "0.0.121", path = "../lightning", default-features = false }
2525
secp256k1 = { version = "0.27.0", default-features = false, features = ["recovery", "alloc"] }
26-
num-traits = { version = "0.2.8", default-features = false }
2726
serde = { version = "1.0.118", optional = true }
2827
bitcoin = { version = "0.30.2", default-features = false }
2928

lightning-invoice/src/de.rs

Lines changed: 31 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@ use lightning::ln::PaymentSecret;
1818
use lightning::routing::gossip::RoutingFees;
1919
use lightning::routing::router::{RouteHint, RouteHintHop};
2020

21-
use num_traits::{CheckedAdd, CheckedMul};
22-
2321
use secp256k1::ecdsa::{RecoveryId, RecoverableSignature};
2422
use secp256k1::PublicKey;
2523

@@ -356,7 +354,7 @@ impl FromBase32 for PositiveTimestamp {
356354
if b32.len() != 7 {
357355
return Err(Bolt11ParseError::InvalidSliceLength("PositiveTimestamp::from_base32()".into()));
358356
}
359-
let timestamp: u64 = parse_int_be(b32, 32)
357+
let timestamp: u64 = parse_u64_be(b32)
360358
.expect("7*5bit < 64bit, no overflow possible");
361359
match PositiveTimestamp::from_unix_timestamp(timestamp) {
362360
Ok(t) => Ok(t),
@@ -382,16 +380,17 @@ impl FromBase32 for Bolt11InvoiceSignature {
382380
}
383381
}
384382

385-
pub(crate) fn parse_int_be<T, U>(digits: &[U], base: T) -> Option<T>
386-
where T: CheckedAdd + CheckedMul + From<u8> + Default,
387-
U: Into<u8> + Copy
388-
{
389-
digits.iter().fold(Some(Default::default()), |acc, b|
390-
acc
391-
.and_then(|x| x.checked_mul(&base))
392-
.and_then(|x| x.checked_add(&(Into::<u8>::into(*b)).into()))
393-
)
394-
}
383+
macro_rules! define_parse_int_be { ($name: ident, $ty: ty) => {
384+
fn $name(digits: &[u5]) -> Option<$ty> {
385+
digits.iter().fold(Some(Default::default()), |acc, b|
386+
acc
387+
.and_then(|x| x.checked_mul(32))
388+
.and_then(|x| x.checked_add((Into::<u8>::into(*b)).into()))
389+
)
390+
}
391+
} }
392+
define_parse_int_be!(parse_u16_be, u16);
393+
define_parse_int_be!(parse_u64_be, u64);
395394

396395
fn parse_tagged_parts(data: &[u5]) -> Result<Vec<RawTaggedField>, Bolt11ParseError> {
397396
let mut parts = Vec::<RawTaggedField>::new();
@@ -404,7 +403,7 @@ fn parse_tagged_parts(data: &[u5]) -> Result<Vec<RawTaggedField>, Bolt11ParseErr
404403

405404
// Ignore tag at data[0], it will be handled in the TaggedField parsers and
406405
// parse the length to find the end of the tagged field's data
407-
let len = parse_int_be(&data[1..3], 32).expect("can't overflow");
406+
let len = parse_u16_be(&data[1..3]).expect("can't overflow") as usize;
408407
let last_element = 3 + len;
409408

410409
if data.len() < last_element {
@@ -517,7 +516,7 @@ impl FromBase32 for ExpiryTime {
517516
type Err = Bolt11ParseError;
518517

519518
fn from_base32(field_data: &[u5]) -> Result<ExpiryTime, Bolt11ParseError> {
520-
match parse_int_be::<u64, u5>(field_data, 32)
519+
match parse_u64_be(field_data)
521520
.map(ExpiryTime::from_seconds)
522521
{
523522
Some(t) => Ok(t),
@@ -530,7 +529,7 @@ impl FromBase32 for MinFinalCltvExpiryDelta {
530529
type Err = Bolt11ParseError;
531530

532531
fn from_base32(field_data: &[u5]) -> Result<MinFinalCltvExpiryDelta, Bolt11ParseError> {
533-
let expiry = parse_int_be::<u64, u5>(field_data, 32);
532+
let expiry = parse_u64_be(field_data);
534533
if let Some(expiry) = expiry {
535534
Ok(MinFinalCltvExpiryDelta(expiry))
536535
} else {
@@ -602,12 +601,12 @@ impl FromBase32 for PrivateRoute {
602601

603602
let hop = RouteHintHop {
604603
src_node_id: PublicKey::from_slice(&hop_bytes[0..33])?,
605-
short_channel_id: parse_int_be(&channel_id, 256).expect("short chan ID slice too big?"),
604+
short_channel_id: u64::from_be_bytes(channel_id),
606605
fees: RoutingFees {
607-
base_msat: parse_int_be(&hop_bytes[41..45], 256).expect("slice too big?"),
608-
proportional_millionths: parse_int_be(&hop_bytes[45..49], 256).expect("slice too big?"),
606+
base_msat: u32::from_be_bytes(hop_bytes[41..45].try_into().expect("slice too big?")),
607+
proportional_millionths: u32::from_be_bytes(hop_bytes[45..49].try_into().expect("slice too big?")),
609608
},
610-
cltv_expiry_delta: parse_int_be(&hop_bytes[49..51], 256).expect("slice too big?"),
609+
cltv_expiry_delta: u16::from_be_bytes(hop_bytes[49..51].try_into().expect("slice too big?")),
611610
htlc_minimum_msat: None,
612611
htlc_maximum_msat: None,
613612
};
@@ -761,12 +760,16 @@ mod test {
761760

762761
#[test]
763762
fn test_parse_int_from_bytes_be() {
764-
use crate::de::parse_int_be;
765-
766-
assert_eq!(parse_int_be::<u32, u8>(&[1, 2, 3, 4], 256), Some(16909060));
767-
assert_eq!(parse_int_be::<u32, u8>(&[1, 3], 32), Some(35));
768-
assert_eq!(parse_int_be::<u32, u8>(&[255, 255, 255, 255], 256), Some(4294967295));
769-
assert_eq!(parse_int_be::<u32, u8>(&[1, 0, 0, 0, 0], 256), None);
763+
use crate::de::parse_u16_be;
764+
765+
assert_eq!(parse_u16_be(&[
766+
u5::try_from_u8(1).unwrap(), u5::try_from_u8(2).unwrap(),
767+
u5::try_from_u8(3).unwrap(), u5::try_from_u8(4).unwrap()]
768+
), Some(34916));
769+
assert_eq!(parse_u16_be(&[
770+
u5::try_from_u8(2).unwrap(), u5::try_from_u8(0).unwrap(),
771+
u5::try_from_u8(0).unwrap(), u5::try_from_u8(0).unwrap()]
772+
), None);
770773
}
771774

772775
#[test]
@@ -916,7 +919,6 @@ mod test {
916919
use lightning::routing::router::{RouteHint, RouteHintHop};
917920
use crate::PrivateRoute;
918921
use bech32::FromBase32;
919-
use crate::de::parse_int_be;
920922

921923
let input = from_bech32(
922924
"q20q82gphp2nflc7jtzrcazrra7wwgzxqc8u7754cdlpfrmccae92qgzqvzq2ps8pqqqqqqpqqqqq9qqqvpeuqa\
@@ -932,7 +934,7 @@ mod test {
932934
0x7e, 0x14, 0x8f, 0x78, 0xc7, 0x72, 0x55
933935
][..]
934936
).unwrap(),
935-
short_channel_id: parse_int_be(&[0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08], 256).expect("short chan ID slice too big?"),
937+
short_channel_id: 0x0102030405060708,
936938
fees: RoutingFees {
937939
base_msat: 1,
938940
proportional_millionths: 20,
@@ -949,7 +951,7 @@ mod test {
949951
0x7e, 0x14, 0x8f, 0x78, 0xc7, 0x72, 0x55
950952
][..]
951953
).unwrap(),
952-
short_channel_id: parse_int_be(&[0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a], 256).expect("short chan ID slice too big?"),
954+
short_channel_id: 0x030405060708090a,
953955
fees: RoutingFees {
954956
base_msat: 2,
955957
proportional_millionths: 30,

lightning-invoice/src/lib.rs

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,6 @@ pub mod utils;
3131

3232
extern crate bech32;
3333
#[macro_use] extern crate lightning;
34-
extern crate num_traits;
3534
extern crate secp256k1;
3635
extern crate alloc;
3736
#[cfg(any(test, feature = "std"))]
@@ -2064,7 +2063,7 @@ mod test {
20642063
let route_1 = RouteHint(vec![
20652064
RouteHintHop {
20662065
src_node_id: public_key,
2067-
short_channel_id: de::parse_int_be(&[123; 8], 256).expect("short chan ID slice too big?"),
2066+
short_channel_id: u64::from_be_bytes([123; 8]),
20682067
fees: RoutingFees {
20692068
base_msat: 2,
20702069
proportional_millionths: 1,
@@ -2075,7 +2074,7 @@ mod test {
20752074
},
20762075
RouteHintHop {
20772076
src_node_id: public_key,
2078-
short_channel_id: de::parse_int_be(&[42; 8], 256).expect("short chan ID slice too big?"),
2077+
short_channel_id: u64::from_be_bytes([42; 8]),
20792078
fees: RoutingFees {
20802079
base_msat: 3,
20812080
proportional_millionths: 2,
@@ -2100,7 +2099,7 @@ mod test {
21002099
},
21012100
RouteHintHop {
21022101
src_node_id: public_key,
2103-
short_channel_id: de::parse_int_be(&[1; 8], 256).expect("short chan ID slice too big?"),
2102+
short_channel_id: u64::from_be_bytes([1; 8]),
21042103
fees: RoutingFees {
21052104
base_msat: 5,
21062105
proportional_millionths: 4,

0 commit comments

Comments
 (0)