Add RLP encoding/decoding for RawCapabilityMessage (#14638) (#14661)

Co-authored-by: Matthias Seitz <matthias.seitz@outlook.de>
This commit is contained in:
Stefan Berat
2025-02-24 05:02:03 -05:00
committed by GitHub
parent 33443de09a
commit 426f144420

View File

@ -8,6 +8,7 @@ use crate::{
Capability, EthMessageID, EthVersion, Capability, EthMessageID, EthVersion,
}; };
use alloy_primitives::bytes::Bytes; use alloy_primitives::bytes::Bytes;
use alloy_rlp::{BufMut, Decodable, Encodable};
use derive_more::{Deref, DerefMut}; use derive_more::{Deref, DerefMut};
use std::{ use std::{
borrow::Cow, borrow::Cow,
@ -40,6 +41,30 @@ impl RawCapabilityMessage {
} }
} }
impl Encodable for RawCapabilityMessage {
/// Encodes the `RawCapabilityMessage` into an RLP byte stream.
fn encode(&self, out: &mut dyn BufMut) {
self.id.encode(out);
out.put_slice(&self.payload);
}
/// Returns the total length of the encoded message.
fn length(&self) -> usize {
self.id.length() + self.payload.len()
}
}
impl Decodable for RawCapabilityMessage {
/// Decodes a `RawCapabilityMessage` from an RLP byte stream.
fn decode(buf: &mut &[u8]) -> alloy_rlp::Result<Self> {
let id = usize::decode(buf)?;
let payload = Bytes::copy_from_slice(buf);
*buf = &buf[buf.len()..];
Ok(Self { id, payload })
}
}
/// This represents a shared capability, its version, and its message id offset. /// This represents a shared capability, its version, and its message id offset.
/// ///
/// The [offset](SharedCapability::message_id_offset) is the message ID offset for this shared /// The [offset](SharedCapability::message_id_offset) is the message ID offset for this shared
@ -383,6 +408,8 @@ pub struct UnsupportedCapabilityError {
mod tests { mod tests {
use super::*; use super::*;
use crate::{Capabilities, Capability}; use crate::{Capabilities, Capability};
use alloy_primitives::bytes::Bytes;
use alloy_rlp::{Decodable, Encodable};
#[test] #[test]
fn from_eth_68() { fn from_eth_68() {
@ -542,4 +569,19 @@ mod tests {
let shared_eth = shared.find_by_relative_offset(1 + proto.messages()).unwrap(); let shared_eth = shared.find_by_relative_offset(1 + proto.messages()).unwrap();
assert_eq!(shared_eth.name(), "eth"); assert_eq!(shared_eth.name(), "eth");
} }
#[test]
fn test_raw_capability_rlp() {
let msg = RawCapabilityMessage { id: 1, payload: Bytes::from(vec![0x01, 0x02, 0x03]) };
// Encode the message into bytes
let mut encoded = Vec::new();
msg.encode(&mut encoded);
// Decode the bytes back into RawCapbailitMessage
let decoded = RawCapabilityMessage::decode(&mut &encoded[..]).unwrap();
// Verify that the decoded message matches the original
assert_eq!(msg, decoded);
}
} }