Skip to content

Commit

Permalink
cannon: deserialize preimage key into [u8;32]
Browse files Browse the repository at this point in the history
  • Loading branch information
rbonichon committed Nov 15, 2023
1 parent e0fd2f5 commit aff4454
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 5 deletions.
26 changes: 23 additions & 3 deletions optimism/src/cannon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ where
#[derive(Serialize, Deserialize, Debug)]
pub struct State {
pub memory: Vec<Page>,
#[serde(rename = "preimageKey")]
pub preimage_key: String,
#[serde(rename = "preimageKey", deserialize_with = "to_preimage_key")]
pub preimage_key: [u8; 32],
#[serde(rename = "preimageOffset")]
pub preimage_offset: u32,
pub pc: u32,
Expand All @@ -52,6 +52,26 @@ pub struct State {
pub last_hint: Option<Vec<u8>>,
}

fn to_preimage_key<'de, D>(deserializer: D) -> Result<[u8; 32], D::Error>
where
D: Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
let parts = s.split("x").collect::<Vec<&str>>();
let hex_value: &str = if parts.len() == 1 {
parts[0]
} else {
assert!(parts.len() == 2);
parts[1]
};
assert!(hex_value.len() == 64); // check this is an hexadecimal representation of 32 bytes
let h = hex::decode(hex_value).unwrap_or_else(|_| panic!("Could not hex decode {hex_value}"));
let res: [u8; 32] = h
.try_into()
.unwrap_or_else(|_| panic!("Could not cast vector into 32 bytes array"));
Ok(res)
}

#[derive(Clone, Debug, PartialEq)]
pub enum StepFrequency {
Never,
Expand Down Expand Up @@ -90,7 +110,7 @@ impl ToString for State {
// A very debatable and incomplete, but serviceable, `to_string` implementation.
fn to_string(&self) -> String {
format!(
"memory_size (length): {}\nfirst page size: {}\npreimage key: {}\npreimage offset:{}\npc: {}\nlo: {}\nhi: {}\nregisters:{:#?} ",
"memory_size (length): {}\nfirst page size: {}\npreimage key: {:#?}\npreimage offset:{}\npc: {}\nlo: {}\nhi: {}\nregisters:{:#?} ",
self.memory.len(),
self.memory[0].data.len(),
self.preimage_key,
Expand Down
4 changes: 2 additions & 2 deletions optimism/src/mips/witness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ pub const SCRATCH_SIZE: usize = 25;
pub struct SyscallEnv {
pub heap: u32, // Heap pointer (actually unused in Cannon as of [2023-10-18])
pub preimage_offset: u32,
pub preimage_key: Vec<u8>,
pub preimage_key: [u8; 32],
pub last_hint: Option<Vec<u8>>,
}

impl SyscallEnv {
pub fn create(state: &State) -> Self {
SyscallEnv {
heap: state.heap,
preimage_key: state.preimage_key.as_bytes().to_vec(), // Might not be correct
preimage_key: state.preimage_key,
preimage_offset: state.preimage_offset,
last_hint: state.last_hint.clone(),
}
Expand Down

0 comments on commit aff4454

Please sign in to comment.