]> git.bitcoin.ninja Git - rust-lightning/commitdiff
Expose `impl_writeable_tlv_based` macro
authorOmer Yacine <mariocynicys@gmail.com>
Fri, 6 Jan 2023 08:18:26 +0000 (10:18 +0200)
committerOmer Yacine <mariocynicys@gmail.com>
Mon, 9 Jan 2023 19:16:30 +0000 (21:16 +0200)
Every exported macro needed to have all the macros used inside it:
1- to be exported as well.
2- be called from the `$crate` namespace so it works in other crates.

Some structs in `lightning::util::ser` needed to be made public as they were used inside the exported macros.

Use the macros like this:
```Rust
lightning::impl_writeable_tlv_based!(...)
```

lightning/src/ln/channelmanager.rs
lightning/src/ln/msgs.rs
lightning/src/onion_message/packet.rs
lightning/src/routing/gossip.rs
lightning/src/util/chacha20poly1305rfc.rs
lightning/src/util/mod.rs
lightning/src/util/ser.rs
lightning/src/util/ser_macros.rs

index 03a150e4fe208493dea2480abeba968b5b79a877..ca95b5edfcf6a02da01a94a03ea61541b0592c88 100644 (file)
@@ -6049,7 +6049,7 @@ impl Writeable for ChannelDetails {
 
 impl Readable for ChannelDetails {
        fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               init_and_read_tlv_fields!(reader, {
+               _init_and_read_tlv_fields!(reader, {
                        (1, inbound_scid_alias, option),
                        (2, channel_id, required),
                        (3, channel_type, option),
index 1478f8b6bfb8272795dcd06d8272db926876a959..399feaf6769a63ee6ab416b3100735624c3e87e3 100644 (file)
@@ -821,8 +821,8 @@ pub struct CommitmentUpdate {
 }
 
 /// Messages could have optional fields to use with extended features
-/// As we wish to serialize these differently from Option<T>s (Options get a tag byte, but
-/// OptionalFeild simply gets Present if there are enough bytes to read into it), we have a
+/// As we wish to serialize these differently from `Option<T>`s (`Options` get a tag byte, but
+/// [`OptionalField`] simply gets `Present` if there are enough bytes to read into it), we have a
 /// separate enum type for them.
 /// (C-not exported) due to a free generic in T
 #[derive(Clone, Debug, PartialEq, Eq)]
@@ -1455,14 +1455,14 @@ impl Writeable for OnionHopData {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
                match self.format {
                        OnionHopDataFormat::NonFinalNode { short_channel_id } => {
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (2, HighZeroBytesDroppedBigSize(self.amt_to_forward), required),
                                        (4, HighZeroBytesDroppedBigSize(self.outgoing_cltv_value), required),
                                        (6, short_channel_id, required)
                                });
                        },
                        OnionHopDataFormat::FinalNode { ref payment_data, ref keysend_preimage } => {
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (2, HighZeroBytesDroppedBigSize(self.amt_to_forward), required),
                                        (4, HighZeroBytesDroppedBigSize(self.outgoing_cltv_value), required),
                                        (8, payment_data, option),
@@ -2875,7 +2875,7 @@ mod tests {
                let mut encoded_payload = Vec::new();
                let test_bytes = vec![42u8; 1000];
                if let OnionHopDataFormat::NonFinalNode { short_channel_id } = payload.format {
-                       encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
+                       _encode_varint_length_prefixed_tlv!(&mut encoded_payload, {
                                (1, test_bytes, vec_type),
                                (2, HighZeroBytesDroppedBigSize(payload.amt_to_forward), required),
                                (4, HighZeroBytesDroppedBigSize(payload.outgoing_cltv_value), required),
index 5ff226387107ae23f839dc376d1db15d73c8a345..27c329335c358c0956e4ed09e03447ec96a1ed57 100644 (file)
@@ -166,14 +166,14 @@ impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
        fn write<W: Writer>(&self, w: &mut W) -> Result<(), io::Error> {
                match &self.0 {
                        Payload::Forward(ForwardControlTlvs::Blinded(encrypted_bytes)) => {
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (4, *encrypted_bytes, vec_type)
                                })
                        },
                        Payload::Receive {
                                control_tlvs: ReceiveControlTlvs::Blinded(encrypted_bytes), reply_path, message,
                        } => {
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (2, reply_path, option),
                                        (4, *encrypted_bytes, vec_type),
                                        (message.tlv_type(), message, required)
@@ -181,7 +181,7 @@ impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
                        },
                        Payload::Forward(ForwardControlTlvs::Unblinded(control_tlvs)) => {
                                let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (4, write_adapter, required)
                                })
                        },
@@ -189,7 +189,7 @@ impl<T: CustomOnionMessageContents> Writeable for (Payload<T>, [u8; 32]) {
                                control_tlvs: ReceiveControlTlvs::Unblinded(control_tlvs), reply_path, message,
                        } => {
                                let write_adapter = ChaChaPolyWriteAdapter::new(self.1, &control_tlvs);
-                               encode_varint_length_prefixed_tlv!(w, {
+                               _encode_varint_length_prefixed_tlv!(w, {
                                        (2, reply_path, option),
                                        (4, write_adapter, required),
                                        (message.tlv_type(), message, required)
@@ -212,7 +212,7 @@ impl<H: CustomOnionMessageHandler> ReadableArgs<(SharedSecret, &H)> for Payload<
                let rho = onion_utils::gen_rho_from_shared_secret(&encrypted_tlvs_ss.secret_bytes());
                let mut message_type: Option<u64> = None;
                let mut message = None;
-               decode_tlv_stream!(&mut rd, {
+               decode_tlv_stream_with_custom_tlv_decode!(&mut rd, {
                        (2, reply_path, option),
                        (4, read_adapter, (option: LengthReadableArgs, rho)),
                }, |msg_type, msg_reader| {
index 947df9edae0f2b3a166e96ff704c9c5775e7da8e..d0682d47d7ed15d475791956ac55022825595813 100644 (file)
@@ -673,13 +673,13 @@ impl Writeable for ChannelUpdateInfo {
 
 impl Readable for ChannelUpdateInfo {
        fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               init_tlv_field_var!(last_update, required);
-               init_tlv_field_var!(enabled, required);
-               init_tlv_field_var!(cltv_expiry_delta, required);
-               init_tlv_field_var!(htlc_minimum_msat, required);
-               init_tlv_field_var!(htlc_maximum_msat, option);
-               init_tlv_field_var!(fees, required);
-               init_tlv_field_var!(last_update_message, required);
+               _init_tlv_field_var!(last_update, required);
+               _init_tlv_field_var!(enabled, required);
+               _init_tlv_field_var!(cltv_expiry_delta, required);
+               _init_tlv_field_var!(htlc_minimum_msat, required);
+               _init_tlv_field_var!(htlc_maximum_msat, option);
+               _init_tlv_field_var!(fees, required);
+               _init_tlv_field_var!(last_update_message, required);
 
                read_tlv_fields!(reader, {
                        (0, last_update, required),
@@ -693,13 +693,13 @@ impl Readable for ChannelUpdateInfo {
 
                if let Some(htlc_maximum_msat) = htlc_maximum_msat {
                        Ok(ChannelUpdateInfo {
-                               last_update: init_tlv_based_struct_field!(last_update, required),
-                               enabled: init_tlv_based_struct_field!(enabled, required),
-                               cltv_expiry_delta: init_tlv_based_struct_field!(cltv_expiry_delta, required),
-                               htlc_minimum_msat: init_tlv_based_struct_field!(htlc_minimum_msat, required),
+                               last_update: _init_tlv_based_struct_field!(last_update, required),
+                               enabled: _init_tlv_based_struct_field!(enabled, required),
+                               cltv_expiry_delta: _init_tlv_based_struct_field!(cltv_expiry_delta, required),
+                               htlc_minimum_msat: _init_tlv_based_struct_field!(htlc_minimum_msat, required),
                                htlc_maximum_msat,
-                               fees: init_tlv_based_struct_field!(fees, required),
-                               last_update_message: init_tlv_based_struct_field!(last_update_message, required),
+                               fees: _init_tlv_based_struct_field!(fees, required),
+                               last_update_message: _init_tlv_based_struct_field!(last_update_message, required),
                        })
                } else {
                        Err(DecodeError::InvalidValue)
@@ -820,14 +820,14 @@ impl MaybeReadable for ChannelUpdateInfoDeserWrapper {
 
 impl Readable for ChannelInfo {
        fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               init_tlv_field_var!(features, required);
-               init_tlv_field_var!(announcement_received_time, (default_value, 0));
-               init_tlv_field_var!(node_one, required);
+               _init_tlv_field_var!(features, required);
+               _init_tlv_field_var!(announcement_received_time, (default_value, 0));
+               _init_tlv_field_var!(node_one, required);
                let mut one_to_two_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
-               init_tlv_field_var!(node_two, required);
+               _init_tlv_field_var!(node_two, required);
                let mut two_to_one_wrap: Option<ChannelUpdateInfoDeserWrapper> = None;
-               init_tlv_field_var!(capacity_sats, required);
-               init_tlv_field_var!(announcement_message, required);
+               _init_tlv_field_var!(capacity_sats, required);
+               _init_tlv_field_var!(announcement_message, required);
                read_tlv_fields!(reader, {
                        (0, features, required),
                        (1, announcement_received_time, (default_value, 0)),
@@ -840,14 +840,14 @@ impl Readable for ChannelInfo {
                });
 
                Ok(ChannelInfo {
-                       features: init_tlv_based_struct_field!(features, required),
-                       node_one: init_tlv_based_struct_field!(node_one, required),
+                       features: _init_tlv_based_struct_field!(features, required),
+                       node_one: _init_tlv_based_struct_field!(node_one, required),
                        one_to_two: one_to_two_wrap.map(|w| w.0).unwrap_or(None),
-                       node_two: init_tlv_based_struct_field!(node_two, required),
+                       node_two: _init_tlv_based_struct_field!(node_two, required),
                        two_to_one: two_to_one_wrap.map(|w| w.0).unwrap_or(None),
-                       capacity_sats: init_tlv_based_struct_field!(capacity_sats, required),
-                       announcement_message: init_tlv_based_struct_field!(announcement_message, required),
-                       announcement_received_time: init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
+                       capacity_sats: _init_tlv_based_struct_field!(capacity_sats, required),
+                       announcement_message: _init_tlv_based_struct_field!(announcement_message, required),
+                       announcement_received_time: _init_tlv_based_struct_field!(announcement_received_time, (default_value, 0)),
                })
        }
 }
@@ -1103,9 +1103,9 @@ impl MaybeReadable for NodeAnnouncementInfoDeserWrapper {
 
 impl Readable for NodeInfo {
        fn read<R: io::Read>(reader: &mut R) -> Result<Self, DecodeError> {
-               init_tlv_field_var!(lowest_inbound_channel_fees, option);
+               _init_tlv_field_var!(lowest_inbound_channel_fees, option);
                let mut announcement_info_wrap: Option<NodeAnnouncementInfoDeserWrapper> = None;
-               init_tlv_field_var!(channels, vec_type);
+               _init_tlv_field_var!(channels, vec_type);
 
                read_tlv_fields!(reader, {
                        (0, lowest_inbound_channel_fees, option),
@@ -1114,9 +1114,9 @@ impl Readable for NodeInfo {
                });
 
                Ok(NodeInfo {
-                       lowest_inbound_channel_fees: init_tlv_based_struct_field!(lowest_inbound_channel_fees, option),
+                       lowest_inbound_channel_fees: _init_tlv_based_struct_field!(lowest_inbound_channel_fees, option),
                        announcement_info: announcement_info_wrap.map(|w| w.0),
-                       channels: init_tlv_based_struct_field!(channels, vec_type),
+                       channels: _init_tlv_based_struct_field!(channels, vec_type),
                })
        }
 }
index 552226ca3e64121569cd2ff65589152255db9c05..052968377a5e58fe6a4236c0812718a236eaab54 100644 (file)
@@ -411,7 +411,7 @@ mod tests {
        #[test]
        fn chacha_stream_adapters_ser_macros() {
                // Test that our stream adapters work as expected with the TLV macros.
-               // This also serves to test the `option: $trait` variant of the `decode_tlv` ser macro.
+               // This also serves to test the `option: $trait` variant of the `_decode_tlv` ser macro.
                do_chacha_stream_adapters_ser_macros().unwrap()
        }
 }
index 730131f224197dc38e5719be8db2336b92089eae..1d46865b6019b0158659ccab2c590c419416e36c 100644 (file)
@@ -13,7 +13,7 @@
 pub(crate) mod fuzz_wrappers;
 
 #[macro_use]
-pub(crate) mod ser_macros;
+pub mod ser_macros;
 
 pub mod events;
 pub mod errors;
index 02d4a81b39e4418daf45f6cb6fc6f61180b1785e..0f88ccbd544c604f84a4a460f4d30a12d51ab200 100644 (file)
@@ -84,7 +84,7 @@ impl Writer for VecWriter {
 
 /// Writer that only tracks the amount of data written - useful if you need to calculate the length
 /// of some data when serialized but don't yet need the full data.
-pub(crate) struct LengthCalculatingWriter(pub usize);
+pub struct LengthCalculatingWriter(pub usize);
 impl Writer for LengthCalculatingWriter {
        #[inline]
        fn write_all(&mut self, buf: &[u8]) -> Result<(), io::Error> {
@@ -93,23 +93,26 @@ impl Writer for LengthCalculatingWriter {
        }
 }
 
-/// Essentially std::io::Take but a bit simpler and with a method to walk the underlying stream
+/// Essentially [`std::io::Take`] but a bit simpler and with a method to walk the underlying stream
 /// forward to ensure we always consume exactly the fixed length specified.
-pub(crate) struct FixedLengthReader<R: Read> {
+pub struct FixedLengthReader<R: Read> {
        read: R,
        bytes_read: u64,
        total_bytes: u64,
 }
 impl<R: Read> FixedLengthReader<R> {
+       /// Returns a new [`FixedLengthReader`].
        pub fn new(read: R, total_bytes: u64) -> Self {
                Self { read, bytes_read: 0, total_bytes }
        }
 
+       /// Returns whether some bytes are remaining or not.
        #[inline]
        pub fn bytes_remain(&mut self) -> bool {
                self.bytes_read != self.total_bytes
        }
 
+       /// Consumes the remaining bytes.
        #[inline]
        pub fn eat_remaining(&mut self) -> Result<(), DecodeError> {
                copy(self, &mut sink()).unwrap();
@@ -145,13 +148,15 @@ impl<R: Read> LengthRead for FixedLengthReader<R> {
        }
 }
 
-/// A Read which tracks whether any bytes have been read at all. This allows us to distinguish
+/// A [`Read`] implementation which tracks whether any bytes have been read at all. This allows us to distinguish
 /// between "EOF reached before we started" and "EOF reached mid-read".
-pub(crate) struct ReadTrackingReader<R: Read> {
+pub struct ReadTrackingReader<R: Read> {
        read: R,
+       /// Returns whether we have read from this reader or not yet.
        pub have_read: bool,
 }
 impl<R: Read> ReadTrackingReader<R> {
+       /// Returns a new [`ReadTrackingReader`].
        pub fn new(read: R) -> Self {
                Self { read, have_read: false }
        }
@@ -278,7 +283,8 @@ impl<T: Readable> MaybeReadable for T {
        }
 }
 
-pub(crate) struct OptionDeserWrapper<T: Readable>(pub Option<T>);
+/// Wrapper to read a required (non-optional) TLV record.
+pub struct OptionDeserWrapper<T: Readable>(pub Option<T>);
 impl<T: Readable> Readable for OptionDeserWrapper<T> {
        #[inline]
        fn read<R: Read>(reader: &mut R) -> Result<Self, DecodeError> {
@@ -528,7 +534,7 @@ impl Readable for [u16; 8] {
 
 /// For variable-length values within TLV record where the length is encoded as part of the record.
 /// Used to prevent encoding the length twice.
-pub(crate) struct WithoutLength<T>(pub T);
+pub struct WithoutLength<T>(pub T);
 
 impl Writeable for WithoutLength<&String> {
        #[inline]
index d37a841eaff31945ecc2af27d624ca8570552006..2ed3683f43fe6938d2fec9118d5f2c2bcb45bda7 100644 (file)
@@ -7,9 +7,19 @@
 // You may not use this file except in accordance with one or both of these
 // licenses.
 
-macro_rules! encode_tlv {
+//! Some macros that implement [`Readable`]/[`Writeable`] traits for lightning messages.
+//! They also handle serialization and deserialization of TLVs.
+//!
+//! [`Readable`]: crate::util::ser::Readable
+//! [`Writeable`]: crate::util::ser::Writeable
+
+/// Implements serialization for a single TLV record.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _encode_tlv {
        ($stream: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
-               encode_tlv!($stream, $type, $field, required)
+               $crate::_encode_tlv!($stream, $type, $field, required)
        };
        ($stream: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
                let _ = &$field; // Ensure we "use" the $field
@@ -20,7 +30,7 @@ macro_rules! encode_tlv {
                $field.write($stream)?;
        };
        ($stream: expr, $type: expr, $field: expr, vec_type) => {
-               encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
+               $crate::_encode_tlv!($stream, $type, $crate::util::ser::WithoutLength(&$field), required);
        };
        ($stream: expr, $optional_type: expr, $optional_field: expr, option) => {
                if let Some(ref field) = $optional_field {
@@ -30,15 +40,18 @@ macro_rules! encode_tlv {
                }
        };
        ($stream: expr, $type: expr, $field: expr, (option, encoding: ($fieldty: ty, $encoding: ident))) => {
-               encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
+               $crate::_encode_tlv!($stream, $type, $field.map(|f| $encoding(f)), option);
        };
        ($stream: expr, $type: expr, $field: expr, (option, encoding: $fieldty: ty)) => {
-               encode_tlv!($stream, $type, $field, option);
+               $crate::_encode_tlv!($stream, $type, $field, option);
        };
 }
 
-
-macro_rules! check_encoded_tlv_order {
+/// Panics if the last seen TLV type is not numerically less than the TLV type currently being checked.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _check_encoded_tlv_order {
        ($last_type: expr, $type: expr, (static_value, $value: expr)) => { };
        ($last_type: expr, $type: expr, $fieldty: tt) => {
                if let Some(t) = $last_type {
@@ -48,6 +61,45 @@ macro_rules! check_encoded_tlv_order {
        };
 }
 
+/// Implements the TLVs serialization part in a [`Writeable`] implementation of a struct.
+///
+/// This should be called inside a method which returns `Result<_, `[`io::Error`]`>`, such as
+/// [`Writeable::write`]. It will only return an `Err` if the stream `Err`s or [`Writeable::write`]
+/// on one of the fields `Err`s.
+///
+/// `$stream` must be a `&mut `[`Writer`] which will receive the bytes for each TLV in the stream.
+///
+/// Fields MUST be sorted in `$type`-order.
+///
+/// Note that the lightning TLV requirements require that a single type not appear more than once,
+/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
+/// decoder.
+///
+/// Any `option` fields which have a value of `None` will not be serialized at all.
+///
+/// For example,
+/// ```
+/// # use lightning::encode_tlv_stream;
+/// # fn write<W: lightning::util::ser::Writer> (stream: &mut W) -> Result<(), lightning::io::Error> {
+/// let mut required_value = 0u64;
+/// let mut optional_value: Option<u64> = None;
+/// encode_tlv_stream!(stream, {
+///     (0, required_value, required),
+///     (1, Some(42u64), option),
+///     (2, optional_value, option),
+/// });
+/// // At this point `required_value` has been written as a TLV of type 0, `42u64` has been written
+/// // as a TLV of type 1 (indicating the reader may ignore it if it is not understood), and *no*
+/// // TLV is written with type 2.
+/// # Ok(())
+/// # }
+/// ```
+///
+/// [`Writeable`]: crate::util::ser::Writeable
+/// [`io::Error`]: crate::io::Error
+/// [`Writeable::write`]: crate::util::ser::Writeable::write
+/// [`Writer`]: crate::util::ser::Writer
+#[macro_export]
 macro_rules! encode_tlv_stream {
        ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => { {
                #[allow(unused_imports)]
@@ -55,10 +107,11 @@ macro_rules! encode_tlv_stream {
                        ln::msgs::DecodeError,
                        util::ser,
                        util::ser::BigSize,
+                       util::ser::Writeable,
                };
 
                $(
-                       encode_tlv!($stream, $type, $field, $fieldty);
+                       $crate::_encode_tlv!($stream, $type, $field, $fieldty);
                )*
 
                #[allow(unused_mut, unused_variables, unused_assignments)]
@@ -66,15 +119,21 @@ macro_rules! encode_tlv_stream {
                {
                        let mut last_seen: Option<u64> = None;
                        $(
-                               check_encoded_tlv_order!(last_seen, $type, $fieldty);
+                               $crate::_check_encoded_tlv_order!(last_seen, $type, $fieldty);
                        )*
                }
        } }
 }
 
-macro_rules! get_varint_length_prefixed_tlv_length {
+/// Adds the length of the serialized field to a [`LengthCalculatingWriter`].
+/// This is exported for use by other exported macros, do not use directly.
+///
+/// [`LengthCalculatingWriter`]: crate::util::ser::LengthCalculatingWriter
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _get_varint_length_prefixed_tlv_length {
        ($len: expr, $type: expr, $field: expr, (default_value, $default: expr)) => {
-               get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
+               $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $field, required)
        };
        ($len: expr, $type: expr, $field: expr, (static_value, $value: expr)) => {
        };
@@ -85,7 +144,7 @@ macro_rules! get_varint_length_prefixed_tlv_length {
                $len.0 += field_len;
        };
        ($len: expr, $type: expr, $field: expr, vec_type) => {
-               get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
+               $crate::_get_varint_length_prefixed_tlv_length!($len, $type, $crate::util::ser::WithoutLength(&$field), required);
        };
        ($len: expr, $optional_type: expr, $optional_field: expr, option) => {
                if let Some(ref field) = $optional_field {
@@ -97,25 +156,33 @@ macro_rules! get_varint_length_prefixed_tlv_length {
        };
 }
 
-macro_rules! encode_varint_length_prefixed_tlv {
+/// See the documentation of [`write_tlv_fields`].
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _encode_varint_length_prefixed_tlv {
        ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),*}) => { {
                use $crate::util::ser::BigSize;
                let len = {
                        #[allow(unused_mut)]
                        let mut len = $crate::util::ser::LengthCalculatingWriter(0);
                        $(
-                               get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
+                               $crate::_get_varint_length_prefixed_tlv_length!(len, $type, $field, $fieldty);
                        )*
                        len.0
                };
                BigSize(len as u64).write($stream)?;
-               encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
+               $crate::encode_tlv_stream!($stream, { $(($type, $field, $fieldty)),* });
        } }
 }
 
-macro_rules! check_decoded_tlv_order {
+/// Errors if there are missing required TLV types between the last seen type and the type currently being processed.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _check_decoded_tlv_order {
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
-               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
+               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
                let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
                if invalid_order {
                        $field = $default.into();
@@ -124,7 +191,7 @@ macro_rules! check_decoded_tlv_order {
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, (static_value, $value: expr)) => {
        };
        ($last_seen_type: expr, $typ: expr, $type: expr, $field: ident, required) => {{
-               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
+               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
                let invalid_order = ($last_seen_type.is_none() || $last_seen_type.unwrap() < $type) && $typ.0 > $type;
                if invalid_order {
                        return Err(DecodeError::InvalidValue);
@@ -147,9 +214,13 @@ macro_rules! check_decoded_tlv_order {
        }};
 }
 
-macro_rules! check_missing_tlv {
+/// Errors if there are missing required TLV types after the last seen type.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _check_missing_tlv {
        ($last_seen_type: expr, $type: expr, $field: ident, (default_value, $default: expr)) => {{
-               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
+               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
                let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
                if missing_req_type {
                        $field = $default.into();
@@ -159,7 +230,7 @@ macro_rules! check_missing_tlv {
                $field = $value;
        };
        ($last_seen_type: expr, $type: expr, $field: ident, required) => {{
-               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always true
+               #[allow(unused_comparisons)] // Note that $type may be 0 making the second comparison always false
                let missing_req_type = $last_seen_type.is_none() || $last_seen_type.unwrap() < $type;
                if missing_req_type {
                        return Err(DecodeError::InvalidValue);
@@ -182,9 +253,13 @@ macro_rules! check_missing_tlv {
        }};
 }
 
-macro_rules! decode_tlv {
+/// Implements deserialization for a single TLV record.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _decode_tlv {
        ($reader: expr, $field: ident, (default_value, $default: expr)) => {{
-               decode_tlv!($reader, $field, required)
+               $crate::_decode_tlv!($reader, $field, required)
        }};
        ($reader: expr, $field: ident, (static_value, $value: expr)) => {{
        }};
@@ -211,33 +286,89 @@ macro_rules! decode_tlv {
                };
        }};
        ($reader: expr, $field: ident, (option, encoding: $fieldty: ty)) => {{
-               decode_tlv!($reader, $field, option);
+               $crate::_decode_tlv!($reader, $field, option);
        }};
 }
 
+/// Checks if `$val` matches `$type`.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
 macro_rules! _decode_tlv_stream_match_check {
        ($val: ident, $type: expr, (static_value, $value: expr)) => { false };
        ($val: ident, $type: expr, $fieldty: tt) => { $val == $type }
 }
 
-// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
-// If it is provided, it will be called with the custom type and the `FixedLengthReader` containing
-// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
-// `Ok(false)` if the message type is unknown, and `Err(DecodeError)` if parsing fails.
+/// Implements the TLVs deserialization part in a [`Readable`] implementation of a struct.
+///
+/// This should be called inside a method which returns `Result<_, `[`DecodeError`]`>`, such as
+/// [`Readable::read`]. It will either return an `Err` or ensure all `required` fields have been
+/// read and optionally read `optional` fields.
+///
+/// `$stream` must be a [`Read`] and will be fully consumed, reading until no more bytes remain
+/// (i.e. it returns [`DecodeError::ShortRead`]).
+///
+/// Fields MUST be sorted in `$type`-order.
+///
+/// Note that the lightning TLV requirements require that a single type not appear more than once,
+/// that TLVs are sorted in type-ascending order, and that any even types be understood by the
+/// decoder.
+///
+/// For example,
+/// ```
+/// # use lightning::decode_tlv_stream;
+/// # fn read<R: lightning::io::Read> (stream: R) -> Result<(), lightning::ln::msgs::DecodeError> {
+/// let mut required_value = 0u64;
+/// let mut optional_value: Option<u64> = None;
+/// decode_tlv_stream!(stream, {
+///     (0, required_value, required),
+///     (2, optional_value, option),
+/// });
+/// // At this point, `required_value` has been overwritten with the TLV with type 0.
+/// // `optional_value` may have been overwritten, setting it to `Some` if a TLV with type 2 was
+/// // present.
+/// # Ok(())
+/// # }
+/// ```
+///
+/// [`Readable`]: crate::util::ser::Readable
+/// [`DecodeError`]: crate::ln::msgs::DecodeError
+/// [`Readable::read`]: crate::util::ser::Readable::read
+/// [`Read`]: crate::io::Read
+/// [`DecodeError::ShortRead`]: crate::ln::msgs::DecodeError::ShortRead
+#[macro_export]
 macro_rules! decode_tlv_stream {
+       ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
+               let rewind = |_, _| { unreachable!() };
+               $crate::_decode_tlv_stream_range!($stream, .., rewind, {$(($type, $field, $fieldty)),*});
+       }
+}
+
+/// Similar to [`decode_tlv_stream`] with a custom TLV decoding capabilities.
+///
+/// `$decode_custom_tlv` is a closure that may be optionally provided to handle custom message types.
+/// If it is provided, it will be called with the custom type and the [`FixedLengthReader`] containing
+/// the message contents. It should return `Ok(true)` if the custom message is successfully parsed,
+/// `Ok(false)` if the message type is unknown, and `Err(`[`DecodeError`]`)` if parsing fails.
+///
+/// [`FixedLengthReader`]: crate::util::ser::FixedLengthReader
+/// [`DecodeError`]: crate::ln::msgs::DecodeError
+macro_rules! decode_tlv_stream_with_custom_tlv_decode {
        ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
         $(, $decode_custom_tlv: expr)?) => { {
                let rewind = |_, _| { unreachable!() };
-               use core::ops::RangeBounds;
-               decode_tlv_stream_range!(
+               _decode_tlv_stream_range!(
                        $stream, .., rewind, {$(($type, $field, $fieldty)),*} $(, $decode_custom_tlv)?
                );
        } }
 }
 
-macro_rules! decode_tlv_stream_range {
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _decode_tlv_stream_range {
        ($stream: expr, $range: expr, $rewind: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
         $(, $decode_custom_tlv: expr)?) => { {
+               use core::ops::RangeBounds;
                use $crate::ln::msgs::DecodeError;
                let mut last_seen_type: Option<u64> = None;
                let mut stream_ref = $stream;
@@ -249,7 +380,7 @@ macro_rules! decode_tlv_stream_range {
                                // We track whether any bytes were read during the consensus_decode call to
                                // determine whether we should break or return ShortRead if we get an
                                // UnexpectedEof. This should in every case be largely cosmetic, but its nice to
-                               // pass the TLV test vectors exactly, which requre this distinction.
+                               // pass the TLV test vectors exactly, which require this distinction.
                                let mut tracking_reader = ser::ReadTrackingReader::new(&mut stream_ref);
                                match <$crate::util::ser::BigSize as $crate::util::ser::Readable>::read(&mut tracking_reader) {
                                        Err(DecodeError::ShortRead) => {
@@ -279,9 +410,9 @@ macro_rules! decode_tlv_stream_range {
                                },
                                _ => {},
                        }
-                       // As we read types, make sure we hit every required type:
+                       // As we read types, make sure we hit every required type between `last_seen_type` and `typ`:
                        $({
-                               check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
+                               $crate::_check_decoded_tlv_order!(last_seen_type, typ, $type, $field, $fieldty);
                        })*
                        last_seen_type = Some(typ.0);
 
@@ -289,8 +420,8 @@ macro_rules! decode_tlv_stream_range {
                        let length: ser::BigSize = $crate::util::ser::Readable::read(&mut stream_ref)?;
                        let mut s = ser::FixedLengthReader::new(&mut stream_ref, length.0);
                        match typ.0 {
-                               $(_t if _decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
-                                       decode_tlv!(s, $field, $fieldty);
+                               $(_t if $crate::_decode_tlv_stream_match_check!(_t, $type, $fieldty) => {
+                                       $crate::_decode_tlv!(s, $field, $fieldty);
                                        if s.bytes_remain() {
                                                s.eat_remaining()?; // Return ShortRead if there's actually not enough bytes
                                                return Err(DecodeError::InvalidValue);
@@ -314,7 +445,7 @@ macro_rules! decode_tlv_stream_range {
                }
                // Make sure we got to each required type after we've read every TLV:
                $({
-                       check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
+                       $crate::_check_missing_tlv!(last_seen_type, $type, $field, $fieldty);
                })*
        } }
 }
@@ -331,7 +462,7 @@ macro_rules! impl_writeable_msg {
                impl $crate::util::ser::Readable for $st {
                        fn read<R: $crate::io::Read>(r: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
                                $(let $field = $crate::util::ser::Readable::read(r)?;)*
-                               $(init_tlv_field_var!($tlvfield, $fieldty);)*
+                               $(_init_tlv_field_var!($tlvfield, $fieldty);)*
                                decode_tlv_stream!(r, {$(($type, $tlvfield, $fieldty)),*});
                                Ok(Self {
                                        $($field),*,
@@ -375,12 +506,14 @@ macro_rules! impl_writeable {
 ///               object.
 /// $min_version_that_can_read_this is the minimum reader version which can understand this
 ///                                 serialized object. Previous versions will simply err with a
-///                                 DecodeError::UnknownVersion.
+///                                 [`DecodeError::UnknownVersion`].
 ///
-/// Updates to either $this_version or $min_version_that_can_read_this should be included in
+/// Updates to either `$this_version` or `$min_version_that_can_read_this` should be included in
 /// release notes.
 ///
 /// Both version fields can be specific to this type of object.
+///
+/// [`DecodeError::UnknownVersion`]: crate::ln::msgs::DecodeError::UnknownVersion
 macro_rules! write_ver_prefix {
        ($stream: expr, $this_version: expr, $min_version_that_can_read_this: expr) => {
                $stream.write_all(&[$this_version; 1])?;
@@ -388,23 +521,26 @@ macro_rules! write_ver_prefix {
        }
 }
 
-/// Writes out a suffix to an object which contains potentially backwards-compatible, optional
-/// fields which old nodes can happily ignore.
+/// Writes out a suffix to an object as a length-prefixed TLV stream which contains potentially
+/// backwards-compatible, optional fields which old nodes can happily ignore.
 ///
 /// It is written out in TLV format and, as with all TLV fields, unknown even fields cause a
-/// DecodeError::UnknownRequiredFeature error, with unknown odd fields ignored.
+/// [`DecodeError::UnknownRequiredFeature`] error, with unknown odd fields ignored.
 ///
 /// This is the preferred method of adding new fields that old nodes can ignore and still function
 /// correctly.
+///
+/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
+#[macro_export]
 macro_rules! write_tlv_fields {
        ($stream: expr, {$(($type: expr, $field: expr, $fieldty: tt)),* $(,)*}) => {
-               encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
+               $crate::_encode_varint_length_prefixed_tlv!($stream, {$(($type, $field, $fieldty)),*})
        }
 }
 
-/// Reads a prefix added by write_ver_prefix!(), above. Takes the current version of the
+/// Reads a prefix added by [`write_ver_prefix`], above. Takes the current version of the
 /// serialization logic for this object. This is compared against the
-/// $min_version_that_can_read_this added by write_ver_prefix!().
+/// `$min_version_that_can_read_this` added by [`write_ver_prefix`].
 macro_rules! read_ver_prefix {
        ($stream: expr, $this_version: expr) => { {
                let ver: u8 = Readable::read($stream)?;
@@ -416,17 +552,24 @@ macro_rules! read_ver_prefix {
        } }
 }
 
-/// Reads a suffix added by write_tlv_fields.
+/// Reads a suffix added by [`write_tlv_fields`].
+///
+/// [`write_tlv_fields`]: crate::write_tlv_fields
+#[macro_export]
 macro_rules! read_tlv_fields {
        ($stream: expr, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => { {
                let tlv_len: $crate::util::ser::BigSize = $crate::util::ser::Readable::read($stream)?;
                let mut rd = $crate::util::ser::FixedLengthReader::new($stream, tlv_len.0);
-               decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
+               $crate::decode_tlv_stream!(&mut rd, {$(($type, $field, $fieldty)),*});
                rd.eat_remaining().map_err(|_| $crate::ln::msgs::DecodeError::ShortRead)?;
        } }
 }
 
-macro_rules! init_tlv_based_struct_field {
+/// Initializes the struct fields.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _init_tlv_based_struct_field {
        ($field: ident, (default_value, $default: expr)) => {
                $field.0.unwrap()
        };
@@ -444,7 +587,11 @@ macro_rules! init_tlv_based_struct_field {
        };
 }
 
-macro_rules! init_tlv_field_var {
+/// Initializes the variable we are going to read the TLV into.
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _init_tlv_field_var {
        ($field: ident, (default_value, $default: expr)) => {
                let mut $field = $crate::util::ser::OptionDeserWrapper(None);
        };
@@ -462,28 +609,54 @@ macro_rules! init_tlv_field_var {
        };
 }
 
-macro_rules! init_and_read_tlv_fields {
+/// Equivalent to running [`_init_tlv_field_var`] then [`read_tlv_fields`].
+/// This is exported for use by other exported macros, do not use directly.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! _init_and_read_tlv_fields {
        ($reader: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
                $(
-                       init_tlv_field_var!($field, $fieldty);
+                       $crate::_init_tlv_field_var!($field, $fieldty);
                )*
 
-               read_tlv_fields!($reader, {
+               $crate::read_tlv_fields!($reader, {
                        $(($type, $field, $fieldty)),*
                });
        }
 }
 
-/// Implements Readable/Writeable for a struct storing it as a set of TLVs
-/// If $fieldty is `required`, then $field is a required field that is not an Option nor a Vec.
-/// If $fieldty is `option`, then $field is optional field.
-/// if $fieldty is `vec_type`, then $field is a Vec, which needs to have its individual elements
-/// serialized.
+/// Implements [`Readable`]/[`Writeable`] for a struct storing it as a set of TLVs
+/// If `$fieldty` is `required`, then `$field` is a required field that is not an Option nor a Vec.
+/// If `$fieldty` is `(default_value, $default)`, then `$field` will be set to `$default` if not present.
+/// If `$fieldty` is `option`, then `$field` is optional field.
+/// If `$fieldty` is `vec_type`, then `$field` is a Vec, which needs to have its individual elements serialized.
+///
+/// For example,
+/// ```
+/// # use lightning::impl_writeable_tlv_based;
+/// struct LightningMessage {
+///    tlv_integer: u32,
+///    tlv_default_integer: u32,
+///    tlv_optional_integer: Option<u32>,
+///    tlv_vec_type_integer: Vec<u32>,
+/// }
+///
+/// impl_writeable_tlv_based!(LightningMessage, {
+///    (0, tlv_integer, required),
+///    (1, tlv_default_integer, (default_value, 7)),
+///    (2, tlv_optional_integer, option),
+///    (3, tlv_vec_type_integer, vec_type),
+/// });
+/// ```
+///
+/// [`Readable`]: crate::util::ser::Readable
+/// [`Writeable`]: crate::util::ser::Writeable
+#[macro_export]
 macro_rules! impl_writeable_tlv_based {
        ($st: ident, {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}) => {
                impl $crate::util::ser::Writeable for $st {
                        fn write<W: $crate::util::ser::Writer>(&self, writer: &mut W) -> Result<(), $crate::io::Error> {
-                               write_tlv_fields!(writer, {
+                               $crate::write_tlv_fields!(writer, {
                                        $(($type, self.$field, $fieldty)),*
                                });
                                Ok(())
@@ -496,7 +669,7 @@ macro_rules! impl_writeable_tlv_based {
                                        #[allow(unused_mut)]
                                        let mut len = $crate::util::ser::LengthCalculatingWriter(0);
                                        $(
-                                               get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
+                                               $crate::_get_varint_length_prefixed_tlv_length!(len, $type, self.$field, $fieldty);
                                        )*
                                        len.0
                                };
@@ -508,12 +681,12 @@ macro_rules! impl_writeable_tlv_based {
 
                impl $crate::util::ser::Readable for $st {
                        fn read<R: $crate::io::Read>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
-                               init_and_read_tlv_fields!(reader, {
+                               $crate::_init_and_read_tlv_fields!(reader, {
                                        $(($type, $field, $fieldty)),*
                                });
                                Ok(Self {
                                        $(
-                                               $field: init_tlv_based_struct_field!($field, $fieldty)
+                                               $field: $crate::_init_tlv_based_struct_field!($field, $fieldty)
                                        ),*
                                })
                        }
@@ -560,12 +733,12 @@ macro_rules! tlv_stream {
                impl $crate::util::ser::SeekReadable for $name {
                        fn read<R: $crate::io::Read + $crate::io::Seek>(reader: &mut R) -> Result<Self, $crate::ln::msgs::DecodeError> {
                                $(
-                                       init_tlv_field_var!($field, option);
+                                       _init_tlv_field_var!($field, option);
                                )*
                                let rewind = |cursor: &mut R, offset: usize| {
                                        cursor.seek($crate::io::SeekFrom::Current(-(offset as i64))).expect("");
                                };
-                               decode_tlv_stream_range!(reader, $range, rewind, {
+                               _decode_tlv_stream_range!(reader, $range, rewind, {
                                        $(($type, $field, (option, encoding: $fieldty))),*
                                });
 
@@ -621,13 +794,18 @@ macro_rules! _impl_writeable_tlv_based_enum_common {
        }
 }
 
-/// Implement MaybeReadable and Writeable for an enum, with struct variants stored as TLVs and
+/// Implement [`MaybeReadable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and
 /// tuple variants stored directly.
 ///
-/// This is largely identical to `impl_writeable_tlv_based_enum`, except that odd variants will
-/// return `Ok(None)` instead of `Err(UnknownRequiredFeature)`. It should generally be preferred
-/// when `MaybeReadable` is practical instead of just `Readable` as it provides an upgrade path for
+/// This is largely identical to [`impl_writeable_tlv_based_enum`], except that odd variants will
+/// return `Ok(None)` instead of `Err(`[`DecodeError::UnknownRequiredFeature`]`)`. It should generally be preferred
+/// when [`MaybeReadable`] is practical instead of just [`Readable`] as it provides an upgrade path for
 /// new variants to be added which are simply ignored by existing clients.
+///
+/// [`MaybeReadable`]: crate::util::ser::MaybeReadable
+/// [`Writeable`]: crate::util::ser::Writeable
+/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
+/// [`Readable`]: crate::util::ser::Readable
 macro_rules! impl_writeable_tlv_based_enum_upgradable {
        ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
                {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
@@ -646,12 +824,12 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable {
                                                // Because read_tlv_fields creates a labeled loop, we cannot call it twice
                                                // in the same function body. Instead, we define a closure and call it.
                                                let f = || {
-                                                       init_and_read_tlv_fields!(reader, {
+                                                       _init_and_read_tlv_fields!(reader, {
                                                                $(($type, $field, $fieldty)),*
                                                        });
                                                        Ok(Some($st::$variant_name {
                                                                $(
-                                                                       $field: init_tlv_based_struct_field!($field, $fieldty)
+                                                                       $field: _init_tlv_based_struct_field!($field, $fieldty)
                                                                ),*
                                                        }))
                                                };
@@ -669,7 +847,7 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable {
        }
 }
 
-/// Implement Readable and Writeable for an enum, with struct variants stored as TLVs and tuple
+/// Implement [`Readable`] and [`Writeable`] for an enum, with struct variants stored as TLVs and tuple
 /// variants stored directly.
 /// The format is, for example
 /// impl_writeable_tlv_based_enum!(EnumName,
@@ -678,7 +856,11 @@ macro_rules! impl_writeable_tlv_based_enum_upgradable {
 ///   (2, TupleVariantA), (3, TupleVariantB),
 /// );
 /// The type is written as a single byte, followed by any variant data.
-/// Attempts to read an unknown type byte result in DecodeError::UnknownRequiredFeature.
+/// Attempts to read an unknown type byte result in [`DecodeError::UnknownRequiredFeature`].
+///
+/// [`Readable`]: crate::util::ser::Readable
+/// [`Writeable`]: crate::util::ser::Writeable
+/// [`DecodeError::UnknownRequiredFeature`]: crate::ln::msgs::DecodeError::UnknownRequiredFeature
 macro_rules! impl_writeable_tlv_based_enum {
        ($st: ident, $(($variant_id: expr, $variant_name: ident) =>
                {$(($type: expr, $field: ident, $fieldty: tt)),* $(,)*}
@@ -696,12 +878,12 @@ macro_rules! impl_writeable_tlv_based_enum {
                                                // Because read_tlv_fields creates a labeled loop, we cannot call it twice
                                                // in the same function body. Instead, we define a closure and call it.
                                                let f = || {
-                                                       init_and_read_tlv_fields!(reader, {
+                                                       _init_and_read_tlv_fields!(reader, {
                                                                $(($type, $field, $fieldty)),*
                                                        });
                                                        Ok($st::$variant_name {
                                                                $(
-                                                                       $field: init_tlv_based_struct_field!($field, $fieldty)
+                                                                       $field: _init_tlv_based_struct_field!($field, $fieldty)
                                                                ),*
                                                        })
                                                };
@@ -910,27 +1092,27 @@ mod tests {
                let mut stream = VecWriter(Vec::new());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(1, 1u8, required), (42, None::<u64>, option)});
                assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(1, Some(1u8), option)});
                assert_eq!(stream.0, ::hex::decode("03010101").unwrap());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(4, 0xabcdu16, required), (42, None::<u64>, option)});
                assert_eq!(stream.0, ::hex::decode("040402abcd").unwrap());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(42, None::<u64>, option), (0xff, 0xabcdu16, required)});
                assert_eq!(stream.0, ::hex::decode("06fd00ff02abcd").unwrap());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(0, 1u64, required), (42, None::<u64>, option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
                assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
 
                stream.0.clear();
-               encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
+               _encode_varint_length_prefixed_tlv!(&mut stream, {(0, Some(1u64), option), (0xff, HighZeroBytesDroppedBigSize(0u64), required)});
                assert_eq!(stream.0, ::hex::decode("0e00080000000000000001fd00ff00").unwrap());
 
                Ok(())