Skip to content

feat: add bincode compat for receipt envelope #2246

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
131 changes: 131 additions & 0 deletions crates/consensus/src/receipt/envelope.rs
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,137 @@ where
}
}

/// Bincode-compatible [`ReceiptEnvelope`] serde implementation.
#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
pub(crate) mod serde_bincode_compat {
use crate::{Receipt, ReceiptWithBloom, TxType};
use alloc::borrow::Cow;
use alloy_primitives::{Bloom, Log, U8};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_with::{DeserializeAs, SerializeAs};

/// Bincode-compatible [`super::ReceiptEnvelope`] serde implementation.
///
/// Intended to use with the [`serde_with::serde_as`] macro in the following way:
/// ```rust
/// use alloy_consensus::{serde_bincode_compat, ReceiptEnvelope};
/// use serde::{de::DeserializeOwned, Deserialize, Serialize};
/// use serde_with::serde_as;
///
/// #[serde_as]
/// #[derive(Serialize, Deserialize)]
/// struct Data<T: Serialize + DeserializeOwned + Clone + 'static> {
/// #[serde_as(as = "serde_bincode_compat::ReceiptEnvelope<'_, T>")]
/// receipt: ReceiptEnvelope<T>,
/// }
/// ```
#[derive(Debug, Serialize, Deserialize)]
pub struct ReceiptEnvelope<'a, T: Clone = Log> {
#[serde(deserialize_with = "deserde_txtype")]
tx_type: TxType,
success: bool,
cumulative_gas_used: u64,
logs_bloom: Cow<'a, Bloom>,
logs: Cow<'a, [T]>,
}

/// Ensures that txtype is deserialized symmetrically as U8
fn deserde_txtype<'de, D>(deserializer: D) -> Result<TxType, D::Error>
where
D: Deserializer<'de>,
{
let value = U8::deserialize(deserializer)?;
value.to::<u8>().try_into().map_err(serde::de::Error::custom)
}

impl<'a, T: Clone> From<&'a super::ReceiptEnvelope<T>> for ReceiptEnvelope<'a, T> {
fn from(value: &'a super::ReceiptEnvelope<T>) -> Self {
Self {
tx_type: value.tx_type(),
success: value.status(),
cumulative_gas_used: value.cumulative_gas_used(),
logs_bloom: Cow::Borrowed(value.logs_bloom()),
logs: Cow::Borrowed(value.logs()),
}
}
}

impl<'a, T: Clone> From<ReceiptEnvelope<'a, T>> for super::ReceiptEnvelope<T> {
fn from(value: ReceiptEnvelope<'a, T>) -> Self {
let ReceiptEnvelope { tx_type, success, cumulative_gas_used, logs_bloom, logs } = value;
let receipt = ReceiptWithBloom {
receipt: Receipt {
status: success.into(),
cumulative_gas_used,
logs: logs.into_owned(),
},
logs_bloom: logs_bloom.into_owned(),
};
match tx_type {
TxType::Legacy => Self::Legacy(receipt),
TxType::Eip2930 => Self::Eip2930(receipt),
TxType::Eip1559 => Self::Eip1559(receipt),
TxType::Eip4844 => Self::Eip4844(receipt),
TxType::Eip7702 => Self::Eip7702(receipt),
}
}
}

impl<T: Serialize + Clone> SerializeAs<super::ReceiptEnvelope<T>> for ReceiptEnvelope<'_, T> {
fn serialize_as<S>(
source: &super::ReceiptEnvelope<T>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
ReceiptEnvelope::<'_, T>::from(source).serialize(serializer)
}
}

impl<'de, T: Deserialize<'de> + Clone> DeserializeAs<'de, super::ReceiptEnvelope<T>>
for ReceiptEnvelope<'de, T>
{
fn deserialize_as<D>(deserializer: D) -> Result<super::ReceiptEnvelope<T>, D::Error>
where
D: Deserializer<'de>,
{
ReceiptEnvelope::<'_, T>::deserialize(deserializer).map(Into::into)
}
}

#[cfg(test)]
mod tests {
use super::super::{serde_bincode_compat, ReceiptEnvelope};
use alloy_primitives::Log;
use arbitrary::Arbitrary;
use rand::Rng;
use serde::{Deserialize, Serialize};
use serde_with::serde_as;

#[test]
fn test_receipt_evelope_bincode_roundtrip() {
#[serde_as]
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
struct Data {
#[serde_as(as = "serde_bincode_compat::ReceiptEnvelope<'_>")]
transaction: ReceiptEnvelope<Log>,
}

let mut bytes = [0u8; 1024];
rand::thread_rng().fill(bytes.as_mut_slice());
let data = Data {
transaction: ReceiptEnvelope::arbitrary(&mut arbitrary::Unstructured::new(&bytes))
.unwrap(),
};

let encoded = bincode::serialize(&data).unwrap();
let decoded: Data = bincode::deserialize(&encoded).unwrap();
assert_eq!(decoded, data);
}
}
}

#[cfg(test)]
mod test {
#[cfg(feature = "serde")]
Expand Down
2 changes: 1 addition & 1 deletion crates/consensus/src/receipt/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use alloy_eips::Typed2718;
/// Bincode-compatible serde implementations for receipt types.
#[cfg(all(feature = "serde", feature = "serde-bincode-compat"))]
pub(crate) mod serde_bincode_compat {
pub use super::receipts::serde_bincode_compat::*;
pub use super::{envelope::serde_bincode_compat::*, receipts::serde_bincode_compat::*};
}

/// Receipt is the result of a transaction execution.
Expand Down
Loading