util: add support for option with custom encoding
What changed, and why it matters
This commit adds a missing macro rule in a Rust serialization helper so that optional fields can use a custom byte encoding. It is a feature addition with a regression test; there is no indication it fixes a security vulnerability.
No security action required; treat as normal feature/test maintenance.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The change extends _init_tlv_based_struct_field! in lightning/src/util/ser_macros.rs to accept (option, encoding: (...)) patterns, delegating to the existing option initializer. A unit test verifies round-trip serialization for None, Some(0), and Some(255) using HighZeroBytesDroppedBigSize. No unsafe code, no bounds checks, no cryptographic operations, and no bug fix language are present.
Changed components
lightning/src/util/ser_macros.rsInspect captured patch +30 / −0
diff --git a/lightning/src/util/ser_macros.rs b/lightning/src/util/ser_macros.rs
index 647e7c7..86b24e1 100644
--- a/lightning/src/util/ser_macros.rs
+++ b/lightning/src/util/ser_macros.rs
@@ -852,6 +852,9 @@ macro_rules! _init_tlv_based_struct_field {
($field: ident, (required_vec, encoding: ($fieldty: ty, $encoding: ident))) => {
$crate::_init_tlv_based_struct_field!($field, required)
};
+ ($field: ident, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
+ $crate::_init_tlv_based_struct_field!($field, option)
+ };
($field: ident, optional_vec) => {
$field.unwrap()
};
@@ -1924,4 +1927,31 @@ mod tests {
LengthReadable::read_from_fixed_length_buffer(&mut &encoded[..]).unwrap();
assert_eq!(decoded, instance);
}
+
+ #[test]
+ fn test_option_with_encoding() {
+ // Ensure that serializing an option with a specified encoding will survive a ser round
+ // trip for Some and None options.
+ #[derive(PartialEq, Eq, Debug)]
+ struct MyCustomStruct {
+ tlv_field: Option<u64>,
+ }
+
+ impl_writeable_msg!(MyCustomStruct, {}, {
+ (1, tlv_field, (option, encoding: (u64, HighZeroBytesDroppedBigSize))),
+ });
+
+ for tlv_field in [None, Some(0u64), Some(255u64)] {
+ let instance = MyCustomStruct { tlv_field };
+ let encoded = instance.encode();
+ let decoded: MyCustomStruct =
+ LengthReadable::read_from_fixed_length_buffer(&mut &encoded[..]).unwrap();
+ assert_eq!(
+ decoded,
+ MyCustomStruct { tlv_field },
+ "option custom encoding failed for: {:?}",
+ tlv_field
+ );
+ }
+ }
}
Why this scored 17/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.