Skip to main content

revm_bytecode/bytecode/
serde_impl.rs

1use super::{Bytecode, BytecodeKind, JumpTable};
2use primitives::{Address, Bytes};
3use serde::{Deserialize, Serialize};
4
5#[derive(Serialize, Deserialize)]
6enum BytecodeSerde {
7    LegacyAnalyzed {
8        bytecode: Bytes,
9        original_len: usize,
10        jump_table: JumpTable,
11    },
12    Eip7702 {
13        delegated_address: Address,
14    },
15}
16
17impl Serialize for Bytecode {
18    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
19        let repr = match self.kind() {
20            BytecodeKind::LegacyAnalyzed => BytecodeSerde::LegacyAnalyzed {
21                bytecode: self.0.bytecode.clone(),
22                original_len: self.0.original_len,
23                jump_table: self.0.jump_table.clone(),
24            },
25            BytecodeKind::Eip7702 => BytecodeSerde::Eip7702 {
26                delegated_address: self.eip7702_address().unwrap(),
27            },
28        };
29        repr.serialize(serializer)
30    }
31}
32
33impl<'de> Deserialize<'de> for Bytecode {
34    fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
35        match BytecodeSerde::deserialize(deserializer)? {
36            BytecodeSerde::LegacyAnalyzed {
37                bytecode,
38                original_len,
39                ..
40            } => {
41                if original_len > bytecode.len() {
42                    return Err(serde::de::Error::custom(
43                        "original_len is greater than bytecode length",
44                    ));
45                }
46                // Re-analyze from original bytes to ensure padding invariants
47                // are satisfied, rather than trusting the serialized form.
48                Ok(Self::new_legacy(bytecode.slice(..original_len)))
49            }
50            BytecodeSerde::Eip7702 { delegated_address } => {
51                Ok(Self::new_eip7702(delegated_address))
52            }
53        }
54    }
55}