p2p: add V1MessageHeader encoding traits
What changed, and why it matters
This commit adds the missing ability to encode (serialize) Bitcoin P2P v1 message headers, matching the existing decoding support. It is a straightforward feature addition with no security-relevant behavior change.
No security action required. Review as normal code-quality/feature completeness change.
Security signals we found
No strong security signals were identified.
Evidence from the diff
The patch implements Encodable for V1MessageHeader in p2p/src/message.rs, producing a 24-byte header (4-byte magic, 12-byte command, 4-byte little-endian payload length, 4-byte checksum). It uses the project’s existing encoder combinators and matches the protocol documentation. No logic is modified or removed; only serialization traits are added.
Changed components
p2p/src/message.rsV1MessageHeaderInspect captured patch +30 / −0
diff --git a/p2p/src/message.rs b/p2p/src/message.rs
index 59fd0db2..2a1d0a69 100644
--- a/p2p/src/message.rs
+++ b/p2p/src/message.rs
@@ -285,6 +285,36 @@ pub struct V1MessageHeader {
pub checksum: [u8; 4],
}
+impl encoding::Encodable for V1MessageHeader {
+ type Encoder<'e>
+ = V1MessageHeaderEncoder<'e>
+ where
+ Self: 'e;
+
+ #[inline]
+ fn encoder(&self) -> Self::Encoder<'_> {
+ let enc = encoding::Encoder4::new(
+ self.magic.encoder(),
+ self.command.encoder(),
+ encoding::ArrayEncoder::without_length_prefix(self.length.to_le_bytes()),
+ encoding::ArrayEncoder::without_length_prefix(self.checksum),
+ );
+
+ V1MessageHeaderEncoder::new(enc)
+ }
+}
+
+encoding::encoder_newtype! {
+ /// The encoder for the [`V1MessageHeader`] type.
+ pub struct V1MessageHeaderEncoder<'e>(
+ encoding::Encoder4<
+ crate::MagicEncoder<'e>,
+ CommandStringEncoder,
+ encoding::ArrayEncoder<4>,
+ encoding::ArrayEncoder<4>
+ >);
+}
+
type V1MessageHeaderInnerDecoder = encoding::Decoder4<
encoding::ArrayDecoder<4>,
CommandStringDecoder,
Why this scored 15/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.