-
Notifications
You must be signed in to change notification settings - Fork 106
Solidity address <> Miden AccountId helper functions
#2238
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
Changes from 4 commits
Commits
Show all changes
26 commits
Select commit
Hold shift + click to select a range
46143c8
feat: add Solidity<>Miden address type conversion functions
partylikeits1983 3c84da6
fix: formatting
partylikeits1983 c71d9df
refactor: rm unnecessary indirection
partylikeits1983 779ab24
refactor: use crypto util functions
partylikeits1983 a8238b6
refactor: implement suggestions & refactor
partylikeits1983 5dd9c85
refactor: update logic & comments to little endian
partylikeits1983 99bcee7
Update crates/miden-agglayer/src/utils.rs
partylikeits1983 2d0a89a
refactor: improve EthAddress representation clarity and MASM alignment
partylikeits1983 3d45e7f
refactor: simplify ethereum_address_to_account_id proc
partylikeits1983 43cbcf3
fix: clippy
partylikeits1983 049e8be
fix: lint doc check
partylikeits1983 99161e3
refactor: use u32assert2
partylikeits1983 3dc29f6
refactor: simplify from_account_id() & u32 check
partylikeits1983 4c6289d
revert: undo drop addr4 in ethereum_address_to_account_id
partylikeits1983 a1a1c3d
Update crates/miden-agglayer/src/eth_address.rs
partylikeits1983 1264d24
refactor: rename to EthAddressFormat
partylikeits1983 2288c0d
refactor: rearrange EthAddressFormat
partylikeits1983 d9c309a
refactor: rename file to eth_address_format
partylikeits1983 393ee03
Merge branch 'agglayer' into ajl-solidity-type-conversions
partylikeits1983 3c3c29e
fix: update script roots
partylikeits1983 aac64df
refactor: update test & refactor
partylikeits1983 888e787
refactor: refactor .to_elements() method
partylikeits1983 9b7333b
refactor: rename to to_account_id
partylikeits1983 de94d04
fix: lint check
partylikeits1983 7abace4
refactor: rename to eth_address.rs & undo Felt::try_from() changes
partylikeits1983 31b1875
Merge branch 'agglayer' into ajl-solidity-type-conversions
bobbinth File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -80,4 +80,3 @@ pub proc verify_claim_proof | |
| dropw dropw dropw dropw | ||
| push.1 | ||
| end | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,97 @@ | ||
| use miden::core::crypto::hashes::keccak256 | ||
| use miden::core::word | ||
|
|
||
| # CONSTANTS | ||
| # ================================================================================================= | ||
|
|
||
| const U32_MAX=4294967295 | ||
| const TWO_POW_32=4294967296 | ||
|
|
||
| const ERR_NOT_U32="address limb is not u32" | ||
| const ERR_ADDR0_NONZERO="first 4 bytes (addr0) must be zero" | ||
| const ERR_PREFIX_OUT_OF_FIELD="prefix would wrap field modulus" | ||
| const ERR_SUFFIX_OUT_OF_FIELD="suffix would wrap field modulus" | ||
|
|
||
|
|
||
| # ETHEREUM ADDRESS PROCEDURES | ||
| # ================================================================================================= | ||
|
|
||
| #! Hashes an Ethereum address (address[5] type) using Keccak256. | ||
| #! | ||
| #! Inputs: [addr0, addr1, addr2, addr3, addr4] | ||
| #! Outputs: [DIGEST_U32[8]] | ||
| #! | ||
| #! Invocation: exec | ||
| pub proc account_id_to_ethereum_hash | ||
| mem_store.0 | ||
| mem_store.1 | ||
| mem_store.2 | ||
| mem_store.3 | ||
| mem_store.4 | ||
|
|
||
| push.20.0 | ||
| exec.keccak256::hash_bytes | ||
| # Stack: [DIGEST_U32[8]] | ||
| end | ||
|
|
||
| #! Converts an Ethereum address (address[5] type) back into an AccountId [prefix, suffix] type. | ||
| #! | ||
| #! The Ethereum address is represented as 5 u32 felts (20 bytes total) in big-endian format. | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| #! The first 4 bytes must be zero for a valid AccountId conversion. | ||
| #! The remaining 16 bytes are converted into two u64 values (prefix and suffix). | ||
| #! | ||
| #! Inputs: [addr0, addr1, addr2, addr3, addr4] | ||
| #! Outputs: [prefix, suffix] | ||
| #! | ||
| #! Where: | ||
| #! - addr0..addr4 are u32 felts (big-endian) representing the 20-byte Ethereum address | ||
| #! - Each addr[i] represents 4 bytes: addr0=bytes[0..3], addr1=bytes[4..7], etc. | ||
| #! - prefix is the first u64 from bytes[4..11] = (addr1 << 32) | addr2 | ||
| #! - suffix is the second u64 from bytes[12..19] = (addr3 << 32) | addr4 | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| #! | ||
| #! Note: This procedure ensures the packed u64 values don't overflow the field modulus | ||
| #! p = 2^64 - 2^32 + 1 by checking that if the high 32 bits are 0xFFFFFFFF, | ||
| #! then the low 32 bits must be 0. | ||
| #! | ||
| #! Invocation: exec | ||
| pub proc ethereum_address_to_account_id | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| # --- addr0 must be 0 --- | ||
| u32assert.err=ERR_NOT_U32 | ||
| dup eq.0 assert.err=ERR_ADDR0_NONZERO | ||
| drop | ||
| # => [addr1, addr2, addr3, addr4] | ||
|
|
||
| # --- validate u32 limbs (optional but nice) --- | ||
| u32assert.err=ERR_NOT_U32 # addr1 | ||
| dup.1 u32assert.err=ERR_NOT_U32 drop # addr2 | ||
| dup.2 u32assert.err=ERR_NOT_U32 drop # addr3 | ||
| dup.3 u32assert.err=ERR_NOT_U32 drop # addr4 | ||
| # => [addr1, addr2, addr3, addr4] | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| # --- prefix: (addr1 << 32) | addr2 --- | ||
| dup push.U32_MAX eq | ||
| if.true | ||
| dup.1 eq.0 assert.err=ERR_PREFIX_OUT_OF_FIELD | ||
| end | ||
|
|
||
| push.TWO_POW_32 mul | ||
| add | ||
| # => [prefix, addr3, addr4] | ||
|
|
||
| # --- suffix: (addr3 << 32) | addr4 --- | ||
| swap | ||
| # => [addr3, prefix, addr4] | ||
|
|
||
| dup push.U32_MAX eq | ||
| if.true | ||
| dup.2 eq.0 assert.err=ERR_SUFFIX_OUT_OF_FIELD | ||
| end | ||
|
|
||
| push.TWO_POW_32 mul | ||
| movup.2 | ||
| add | ||
| # => [suffix, prefix] | ||
|
|
||
| swap | ||
| # => [prefix, suffix] | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
partylikeits1983 marked this conversation as resolved.
Show resolved
Hide resolved
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,202 @@ | ||
| use alloc::string::String; | ||
| use alloc::vec::Vec; | ||
| use core::fmt; | ||
|
|
||
| use miden_core::FieldElement; | ||
| use miden_protocol::Felt; | ||
| use miden_protocol::account::AccountId; | ||
| use miden_protocol::utils::{HexParseError, bytes_to_hex_string, hex_to_bytes}; | ||
|
|
||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub enum AddrConvError { | ||
| NonZeroWordPadding, | ||
| NonZeroBytePrefix, | ||
| InvalidHexLength, | ||
| InvalidHexChar(char), | ||
| HexParseError, | ||
| } | ||
|
|
||
| impl fmt::Display for AddrConvError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| match self { | ||
| AddrConvError::HexParseError => write!(f, "Hex parse error"), | ||
| _ => write!(f, "{:?}", self), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<HexParseError> for AddrConvError { | ||
| fn from(_err: HexParseError) -> Self { | ||
| AddrConvError::HexParseError | ||
| } | ||
| } | ||
|
|
||
| // ================================================================================================ | ||
| // ETHEREUM ADDRESS | ||
| // ================================================================================================ | ||
|
|
||
| /// Represents an Ethereum address (20 bytes). | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| /// | ||
| /// This type provides conversions between Ethereum addresses and Miden types such as | ||
| /// [`AccountId`] and field elements ([`Felt`]). | ||
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| pub struct EthAddress([u8; 20]); | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| impl EthAddress { | ||
| // CONSTRUCTORS | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Creates a new [`EthAddress`] from a 20-byte array. | ||
| pub const fn new(bytes: [u8; 20]) -> Self { | ||
| Self(bytes) | ||
| } | ||
|
|
||
| /// Creates an [`EthAddress`] from a hex string (with or without "0x" prefix). | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if the hex string is invalid or not 40 characters (20 bytes). | ||
| pub fn from_hex(hex_str: &str) -> Result<Self, AddrConvError> { | ||
| let s = hex_str.strip_prefix("0x").unwrap_or(hex_str); | ||
| if s.len() != 40 { | ||
| return Err(AddrConvError::InvalidHexLength); | ||
| } | ||
|
|
||
| let bytes: [u8; 20] = hex_to_bytes(s)?; | ||
| Ok(Self(bytes)) | ||
| } | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| /// Creates an [`EthAddress`] from an [`AccountId`]. | ||
| /// | ||
| /// The AccountId is converted to an Ethereum address using the embedded format where | ||
| /// the first 4 bytes are zero padding, followed by the prefix and suffix as u64 values | ||
| /// in big-endian format. | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if the conversion fails (e.g., if the AccountId cannot be represented | ||
| /// as a valid Ethereum address). | ||
| pub fn from_account_id(account_id: AccountId) -> Result<Self, AddrConvError> { | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| let felts: [Felt; 2] = account_id.into(); | ||
| let u64x5 = [felts[0].as_int(), felts[1].as_int(), 0, 0, 0]; | ||
| let bytes = Self::u64x5_to_bytes20(u64x5)?; | ||
| Ok(Self(bytes)) | ||
| } | ||
|
|
||
| // CONVERSIONS | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Returns the raw 20-byte array. | ||
| pub const fn as_bytes(&self) -> &[u8; 20] { | ||
| &self.0 | ||
| } | ||
|
|
||
| /// Converts the address into a 20-byte array. | ||
| pub const fn into_bytes(self) -> [u8; 20] { | ||
| self.0 | ||
| } | ||
|
|
||
| /// Converts the Ethereum address into a vector of 5 [`Felt`] values. | ||
| /// | ||
| /// Each felt represents 4 bytes of the address in big-endian format. | ||
| pub fn to_felts(&self) -> Vec<Felt> { | ||
| let mut result = Vec::with_capacity(5); | ||
| for i in 0..5 { | ||
| let start = i * 4; | ||
| let chunk = &self.0[start..start + 4]; | ||
| let value = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); | ||
| result.push(Felt::new(value as u64)); | ||
| } | ||
| result | ||
| } | ||
|
|
||
| /// Converts the Ethereum address into an array of 5 [`Felt`] values. | ||
| /// | ||
| /// Each felt represents 4 bytes of the address in big-endian format. | ||
| pub fn to_felt_array(&self) -> [Felt; 5] { | ||
| let mut result = [Felt::ZERO; 5]; | ||
| for (i, felt) in result.iter_mut().enumerate() { | ||
| let start = i * 4; | ||
| let chunk = &self.0[start..start + 4]; | ||
| let value = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); | ||
| *felt = Felt::new(value as u64); | ||
| } | ||
| result | ||
| } | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| /// Converts the Ethereum address to an [`AccountId`]. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if the first 4 bytes are not zero or if the resulting | ||
| /// AccountId is invalid. | ||
| pub fn to_account_id(&self) -> Result<AccountId, AddrConvError> { | ||
| let u64x5 = Self::bytes20_to_u64x5(self.0)?; | ||
| let felts = [Felt::new(u64x5[0]), Felt::new(u64x5[1])]; | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| match AccountId::try_from(felts) { | ||
| Ok(account_id) => Ok(account_id), | ||
| Err(_) => Err(AddrConvError::NonZeroBytePrefix), | ||
| } | ||
| } | ||
|
|
||
| /// Converts the Ethereum address to a hex string (lowercase, 0x-prefixed). | ||
| pub fn to_hex(&self) -> String { | ||
| let mut s = String::with_capacity(42); | ||
| s.push_str("0x"); | ||
| s.push_str(&bytes_to_hex_string(self.0)); | ||
| s | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| // HELPER FUNCTIONS | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Convert `[u64; 5]` -> `[u8; 20]` (EVM address bytes). | ||
| /// Layout: 4 zero bytes prefix + word0(be) + word1(be) | ||
| fn u64x5_to_bytes20(words: [u64; 5]) -> Result<[u8; 20], AddrConvError> { | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if words[2] != 0 || words[3] != 0 || words[4] != 0 { | ||
| return Err(AddrConvError::NonZeroWordPadding); | ||
| } | ||
|
|
||
| let mut out = [0u8; 20]; | ||
| let w0 = words[0].to_be_bytes(); | ||
| let w1 = words[1].to_be_bytes(); | ||
|
|
||
| out[0..4].copy_from_slice(&[0, 0, 0, 0]); | ||
| out[4..12].copy_from_slice(&w0); | ||
| out[12..20].copy_from_slice(&w1); | ||
|
|
||
| Ok(out) | ||
| } | ||
|
|
||
| /// Convert `[u8; 20]` -> `[u64; 5]` by extracting the last 16 bytes. | ||
| /// Requires the first 4 bytes be zero. | ||
| fn bytes20_to_u64x5(bytes: [u8; 20]) -> Result<[u64; 5], AddrConvError> { | ||
| if bytes[0..4] != [0, 0, 0, 0] { | ||
| return Err(AddrConvError::NonZeroBytePrefix); | ||
| } | ||
|
|
||
| let w0 = u64::from_be_bytes(bytes[4..12].try_into().unwrap()); | ||
| let w1 = u64::from_be_bytes(bytes[12..20].try_into().unwrap()); | ||
|
|
||
| Ok([w0, w1, 0, 0, 0]) | ||
| } | ||
partylikeits1983 marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| } | ||
|
|
||
| impl fmt::Display for EthAddress { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| write!(f, "{}", self.to_hex()) | ||
| } | ||
| } | ||
|
|
||
| impl From<[u8; 20]> for EthAddress { | ||
| fn from(bytes: [u8; 20]) -> Self { | ||
| Self(bytes) | ||
| } | ||
| } | ||
|
|
||
| impl From<EthAddress> for [u8; 20] { | ||
| fn from(addr: EthAddress) -> Self { | ||
| addr.0 | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.