Skip to content

Commit

Permalink
fix: remove reliance on invalid decompositions in selector calculation (
Browse files Browse the repository at this point in the history
#9337)

Decomposing `hash` into `SELECTOR_SIZE` bytes relies on the compiler not
checking the correctness of decompositions performed at compile time.
This means the current code does not work at runtime and we're also
looking to enforce the correctness of this decomposition at
compile-time.

I've replaced this decomposition with a truncation into 32 bits as this
seems equivalent.
  • Loading branch information
TomAFrench authored Oct 23, 2024
1 parent 8e6734e commit c8e4260
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 14 deletions.
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use crate::utils::field::field_from_bytes;
use crate::traits::{Serialize, Deserialize, FromField, ToField, Empty};

global SELECTOR_SIZE: u32 = 4;

pub struct EventSelector {
// 1st 4-bytes (big-endian leftmost) of abi-encoding of an event.
inner: u32,
Expand Down Expand Up @@ -53,10 +50,8 @@ impl EventSelector {
let bytes = signature.as_bytes();
let hash = crate::hash::poseidon2_hash_bytes(bytes);

// We choose the last SELECTOR_SIZE bytes of the hash to avoid getting the first byte that is not full
let hash_bytes = hash.to_be_bytes::<SELECTOR_SIZE>();

EventSelector::from_field(field_from_bytes(hash_bytes, true))
// `hash` is automatically truncated to fit within 32 bits.
EventSelector::from_field(hash)
}

pub fn zero() -> Self {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
use crate::utils::field::field_from_bytes;
use crate::traits::{Serialize, Deserialize, FromField, ToField, Empty};

global SELECTOR_SIZE: u32 = 4;

pub struct FunctionSelector {
// 1st 4-bytes of abi-encoding of function.
inner: u32,
Expand Down Expand Up @@ -53,10 +50,8 @@ impl FunctionSelector {
let bytes = signature.as_bytes();
let hash = crate::hash::poseidon2_hash_bytes(bytes);

// We choose the last SELECTOR_SIZE bytes of the hash to avoid getting the first byte that is not full
let hash_bytes = hash.to_be_bytes::<SELECTOR_SIZE>();

FunctionSelector::from_field(field_from_bytes(hash_bytes, true))
// `hash` is automatically truncated to fit within 32 bits.
FunctionSelector::from_field(hash)
}

pub fn zero() -> Self {
Expand Down

0 comments on commit c8e4260

Please sign in to comment.