From babfa97d959716539073b03b148378e1b744169d Mon Sep 17 00:00:00 2001 From: optout <13562139+optout21@users.noreply.github.com> Date: Fri, 6 Sep 2024 10:03:55 +0200 Subject: [PATCH] Struggle with features serialization/deserialization with iterators --- lightning-invoice/src/de.rs | 22 ++++++++++++++++++++++ lightning-invoice/src/ser.rs | 14 ++++++++++++++ 2 files changed, 36 insertions(+) diff --git a/lightning-invoice/src/de.rs b/lightning-invoice/src/de.rs index 0650a1117aa..fe62076cf89 100644 --- a/lightning-invoice/src/de.rs +++ b/lightning-invoice/src/de.rs @@ -85,6 +85,27 @@ impl FromBase32 for Bolt11InvoiceFeatures { /// and taking the resulting 8-bit values (right to left), /// with the leading 0's skipped. fn from_base32(field_data: &[Fe32]) -> Result { + // fes_to_bytes() trims, input needs to be padded, find padding size + let input_len = field_data.len(); + let mut padding = 0; + while ((input_len + padding) * 5) % 8 != 0 { + padding += 1; + } + let mut output = field_data + .iter() + .map(|f| Fe32::try_from(f.to_u8().reverse_bits() >> 3).expect("<32")) + .rev() + .chain(core::iter::repeat(Fe32::Q).take(padding)) + .fes_to_bytes() + .map(|b| b.reverse_bits()) + .collect::>(); + // Trim the highest feature bits -<-- COULD NOT DO WITH ITER + while !output.is_empty() && output[output.len() - 1] == 0 { + output.pop(); + } + Ok(Bolt11InvoiceFeatures::from_le_bytes(output)) + + /* // Fe32 conversion cannot be used, because this unpacks from right, right-to-left // Carry bits, 0, 1, 2, 3, or 4 bits let mut carry_bits = 0; @@ -116,6 +137,7 @@ impl FromBase32 for Bolt11InvoiceFeatures { output.pop(); } Ok(Bolt11InvoiceFeatures::from_le_bytes(output)) + */ } } diff --git a/lightning-invoice/src/ser.rs b/lightning-invoice/src/ser.rs index 4000241f557..4bfd2689103 100644 --- a/lightning-invoice/src/ser.rs +++ b/lightning-invoice/src/ser.rs @@ -85,6 +85,19 @@ impl Base32Iterable for Bolt11InvoiceFeatures { /// and taking the resulting 5-bit values in reverse (left-to-right), /// with the leading 0's skipped. fn fe_iter<'s>(&'s self) -> Box + 's> { + Box::new( + self + .le_flags() + .iter() + .map(|b| b.reverse_bits()) + .bytes_to_fes() + .collect::>().into_iter() // <-- COULD NOT DO WITHOUT COLLECT + .rev() + .map(|f| Fe32::try_from(f.to_u8().reverse_bits() >> 3).expect("<32")) + .skip_while(|e| *e == Fe32::Q) + ) + + /* // Fe32 conversion cannot be used, because this packs from right, right-to-left let mut input_iter = self.le_flags().iter(); // Carry bits, 0..7 bits @@ -123,6 +136,7 @@ impl Base32Iterable for Bolt11InvoiceFeatures { } // Take result in reverse order, and skip leading 0s Box::new(output.into_iter().rev().skip_while(|e| *e == Fe32::Q)) + */ } }