-
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 all 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
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,88 @@ | ||
| 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_ADDR4_NONZERO="most-significant 4 bytes (addr4) must be zero" | ||
| const ERR_FELT_OUT_OF_FIELD="combined u64 doesn't fit in field" | ||
|
|
||
|
|
||
| # ETHEREUM ADDRESS PROCEDURES | ||
| # ================================================================================================= | ||
|
|
||
| #! Builds a single felt from two u32 limbs (little-endian limb order). | ||
| #! Conceptually, this is packing a 64-bit word (lo + (hi << 32)) into a field element. | ||
| #! This proc additionally verifies that the packed value did *not* reduce mod p by round-tripping | ||
| #! through u32split and comparing the limbs. | ||
| #! | ||
| #! Inputs: [lo, hi] | ||
| #! Outputs: [felt] | ||
| proc build_felt | ||
| # --- validate u32 limbs --- | ||
| u32assert2.err=ERR_NOT_U32 | ||
| # => [lo, hi] | ||
|
|
||
| # keep copies for the overflow check | ||
| dup.1 dup.1 | ||
| # => [lo, hi, lo, hi] | ||
|
|
||
| # felt = (hi * 2^32) + lo | ||
| swap | ||
| push.TWO_POW_32 mul | ||
| add | ||
| # => [felt, lo, hi] | ||
|
|
||
| # ensure no reduction mod p happened: | ||
| # split felt back into (hi, lo) and compare to inputs | ||
| dup u32split | ||
| # => [hi2, lo2, felt, lo, hi] | ||
|
|
||
| movup.4 assert_eq.err=ERR_FELT_OUT_OF_FIELD | ||
| # => [lo2, felt, lo] | ||
|
|
||
| movup.2 assert_eq.err=ERR_FELT_OUT_OF_FIELD | ||
| # => [felt] | ||
| end | ||
|
|
||
| #! Converts an Ethereum address format (address[5] type) back into an AccountId [prefix, suffix] type. | ||
| #! | ||
| #! The Ethereum address format is represented as 5 u32 limbs (20 bytes total) in *little-endian limb order*: | ||
| #! addr0 = bytes[16..19] (least-significant 4 bytes) | ||
| #! addr1 = bytes[12..15] | ||
| #! addr2 = bytes[ 8..11] | ||
| #! addr3 = bytes[ 4.. 7] | ||
| #! addr4 = bytes[ 0.. 3] (most-significant 4 bytes) | ||
| #! | ||
| #! The most-significant 4 bytes must be zero for a valid AccountId conversion (addr4 == 0). | ||
mmagician marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| #! The remaining 16 bytes are treated as two 8-byte words (conceptual u64 values): | ||
| #! prefix = (addr3 << 32) | addr2 # bytes[4..11] | ||
| #! suffix = (addr1 << 32) | addr0 # bytes[12..19] | ||
| #! | ||
| #! These 8-byte words are represented as field elements by packing two u32 limbs into a felt. | ||
| #! The packing is done via build_felt, which validates limbs are u32 and checks the packed value | ||
| #! did not reduce mod p (i.e. the word fits in the field). | ||
| #! | ||
| #! Inputs: [addr0, addr1, addr2, addr3, addr4] | ||
| #! Outputs: [prefix, suffix] | ||
| #! | ||
| #! Invocation: exec | ||
| pub proc to_account_id | ||
| # addr4 must be 0 (most-significant limb) | ||
| movup.4 | ||
| eq.0 assert.err=ERR_ADDR4_NONZERO | ||
| # => [addr0, addr1, addr2, addr3] | ||
|
|
||
| exec.build_felt | ||
| # => [suffix, addr2, addr3] | ||
|
|
||
| movdn.2 | ||
| # => [addr2, addr3, suffix] | ||
|
|
||
| exec.build_felt | ||
| # => [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,243 @@ | ||
| use alloc::format; | ||
| use alloc::string::{String, ToString}; | ||
| 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}; | ||
|
|
||
| // ================================================================================================ | ||
| // ETHEREUM ADDRESS | ||
| // ================================================================================================ | ||
|
|
||
| /// Represents an Ethereum address format (20 bytes). | ||
| /// | ||
| /// # Representations used in this module | ||
| /// | ||
| /// - Raw bytes: `[u8; 20]` in the conventional Ethereum big-endian byte order (`bytes[0]` is the | ||
| /// most-significant byte). | ||
| /// - MASM "address\[5\]" limbs: 5 x u32 limbs in *little-endian limb order*: | ||
| /// - addr0 = bytes[16..19] (least-significant 4 bytes) | ||
| /// - addr1 = bytes[12..15] | ||
| /// - addr2 = bytes[ 8..11] | ||
| /// - addr3 = bytes[ 4.. 7] | ||
| /// - addr4 = bytes[ 0.. 3] (most-significant 4 bytes) | ||
| /// - Embedded AccountId format: `0x00000000 || prefix(8) || suffix(8)`, where: | ||
| /// - prefix = (addr3 << 32) | addr2 = bytes[4..11] as a big-endian u64 | ||
| /// - suffix = (addr1 << 32) | addr0 = bytes[12..19] as a big-endian u64 | ||
| /// | ||
| /// Note: prefix/suffix are *conceptual* 64-bit words; when converting to [`Felt`], we must ensure | ||
| /// `Felt::new(u64)` does not reduce mod p (checked explicitly in `to_account_id`). | ||
| #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] | ||
| pub struct EthAddressFormat([u8; 20]); | ||
|
|
||
| impl EthAddressFormat { | ||
| // EXTERNAL API - For integrators (Gateway, claim managers, etc.) | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Creates a new [`EthAddressFormat`] from a 20-byte array. | ||
| pub const fn new(bytes: [u8; 20]) -> Self { | ||
| Self(bytes) | ||
| } | ||
|
|
||
| /// Creates an [`EthAddressFormat`] from a hex string (with or without "0x" prefix). | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if the hex string is invalid or the hex part is not exactly 40 characters. | ||
| pub fn from_hex(hex_str: &str) -> Result<Self, AddressConversionError> { | ||
| let hex_part = hex_str.strip_prefix("0x").unwrap_or(hex_str); | ||
| if hex_part.len() != 40 { | ||
| return Err(AddressConversionError::InvalidHexLength); | ||
| } | ||
|
|
||
| let prefixed_hex = if hex_str.starts_with("0x") { | ||
| hex_str.to_string() | ||
| } else { | ||
| format!("0x{}", hex_str) | ||
| }; | ||
|
|
||
| let bytes: [u8; 20] = hex_to_bytes(&prefixed_hex)?; | ||
| Ok(Self(bytes)) | ||
| } | ||
|
|
||
| /// Creates an [`EthAddressFormat`] from an [`AccountId`]. | ||
| /// | ||
| /// **External API**: This function is used by integrators (Gateway, claim managers) to convert | ||
| /// Miden AccountIds into the Ethereum address format for constructing CLAIM notes or | ||
| /// interfacing when calling the Agglayer Bridge function bridgeAsset(). | ||
| /// | ||
| /// This conversion is infallible: an [`AccountId`] is two felts, and `as_int()` yields `u64` | ||
| /// words which we embed as `0x00000000 || prefix(8) || suffix(8)` (big-endian words). | ||
| /// | ||
| /// # Example | ||
| /// ```ignore | ||
| /// let destination_address = EthAddressFormat::from_account_id(destination_account_id).into_bytes(); | ||
| /// // then construct the CLAIM note with destination_address... | ||
| /// ``` | ||
| pub fn from_account_id(account_id: AccountId) -> Self { | ||
partylikeits1983 marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| let felts: [Felt; 2] = account_id.into(); | ||
|
|
||
| let mut out = [0u8; 20]; | ||
| out[4..12].copy_from_slice(&felts[0].as_int().to_be_bytes()); | ||
| out[12..20].copy_from_slice(&felts[1].as_int().to_be_bytes()); | ||
|
|
||
| Self(out) | ||
| } | ||
|
|
||
| /// 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 to a hex string (lowercase, 0x-prefixed). | ||
| pub fn to_hex(&self) -> String { | ||
| bytes_to_hex_string(self.0) | ||
| } | ||
|
|
||
| // INTERNAL API - For CLAIM note processing | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Converts the Ethereum address format into an array of 5 [`Felt`] values for MASM processing. | ||
| /// | ||
| /// **Internal API**: This function is used internally during CLAIM note processing to convert | ||
| /// the address format into the MASM `address[5]` representation expected by the | ||
| /// `to_account_id` procedure. | ||
| /// | ||
| /// The returned order matches the MASM `address\[5\]` convention (*little-endian limb order*): | ||
| /// - addr0 = bytes[16..19] (least-significant 4 bytes) | ||
| /// - addr1 = bytes[12..15] | ||
| /// - addr2 = bytes[ 8..11] | ||
| /// - addr3 = bytes[ 4.. 7] | ||
| /// - addr4 = bytes[ 0.. 3] (most-significant 4 bytes) | ||
| /// | ||
| /// Each limb is interpreted as a big-endian `u32` and stored in a [`Felt`]. | ||
| pub fn to_elements(&self) -> [Felt; 5] { | ||
| let mut result = [Felt::ZERO; 5]; | ||
|
|
||
| // i=0 -> bytes[16..20], i=4 -> bytes[0..4] | ||
| for (felt, chunk) in result.iter_mut().zip(self.0.chunks(4).skip(1).rev()) { | ||
| let value = u32::from_be_bytes([chunk[0], chunk[1], chunk[2], chunk[3]]); | ||
| // u32 values always fit in Felt, so this conversion is safe | ||
| *felt = Felt::try_from(value as u64).expect("u32 value should always fit in Felt"); | ||
| } | ||
|
|
||
| result | ||
| } | ||
|
|
||
| /// Converts the Ethereum address format back to an [`AccountId`]. | ||
| /// | ||
| /// **Internal API**: This function is used internally during CLAIM note processing to extract | ||
| /// the original AccountId from the Ethereum address format. It mirrors the functionality of | ||
| /// the MASM `to_account_id` procedure. | ||
| /// | ||
| /// # Errors | ||
| /// | ||
| /// Returns an error if: | ||
| /// - the first 4 bytes are not zero (not in the embedded AccountId format), | ||
| /// - packing the 8-byte prefix/suffix into [`Felt`] would reduce mod p, | ||
| /// - or the resulting felts do not form a valid [`AccountId`]. | ||
| pub fn to_account_id(&self) -> Result<AccountId, AddressConversionError> { | ||
| let (prefix, suffix) = Self::bytes20_to_prefix_suffix(self.0)?; | ||
|
|
||
| // Use `Felt::try_from(u64)` to avoid potential truncating conversion | ||
| let prefix_felt = | ||
| Felt::try_from(prefix).map_err(|_| AddressConversionError::FeltOutOfField)?; | ||
|
|
||
| let suffix_felt = | ||
| Felt::try_from(suffix).map_err(|_| AddressConversionError::FeltOutOfField)?; | ||
|
|
||
| AccountId::try_from([prefix_felt, suffix_felt]) | ||
| .map_err(|_| AddressConversionError::InvalidAccountId) | ||
| } | ||
|
|
||
| // HELPER FUNCTIONS | ||
| // -------------------------------------------------------------------------------------------- | ||
|
|
||
| /// Convert `[u8; 20]` -> `(prefix, suffix)` by extracting the last 16 bytes. | ||
| /// Requires the first 4 bytes be zero. | ||
| /// Returns prefix and suffix values that match the MASM little-endian limb implementation: | ||
| /// - prefix = bytes[4..12] as big-endian u64 = (addr3 << 32) | addr2 | ||
| /// - suffix = bytes[12..20] as big-endian u64 = (addr1 << 32) | addr0 | ||
| fn bytes20_to_prefix_suffix(bytes: [u8; 20]) -> Result<(u64, u64), AddressConversionError> { | ||
| if bytes[0..4] != [0, 0, 0, 0] { | ||
| return Err(AddressConversionError::NonZeroBytePrefix); | ||
| } | ||
|
|
||
| let prefix = u64::from_be_bytes(bytes[4..12].try_into().unwrap()); | ||
| let suffix = u64::from_be_bytes(bytes[12..20].try_into().unwrap()); | ||
|
|
||
| Ok((prefix, suffix)) | ||
| } | ||
| } | ||
|
|
||
| impl fmt::Display for EthAddressFormat { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| write!(f, "{}", self.to_hex()) | ||
| } | ||
| } | ||
|
|
||
| impl From<[u8; 20]> for EthAddressFormat { | ||
| fn from(bytes: [u8; 20]) -> Self { | ||
| Self(bytes) | ||
| } | ||
| } | ||
|
|
||
| impl From<AccountId> for EthAddressFormat { | ||
| fn from(account_id: AccountId) -> Self { | ||
| EthAddressFormat::from_account_id(account_id) | ||
| } | ||
| } | ||
|
|
||
| impl From<EthAddressFormat> for [u8; 20] { | ||
| fn from(addr: EthAddressFormat) -> Self { | ||
| addr.0 | ||
| } | ||
| } | ||
|
|
||
| // ================================================================================================ | ||
| // ADDRESS CONVERSION ERROR | ||
| // ================================================================================================ | ||
|
|
||
| #[derive(Debug, Clone, PartialEq, Eq)] | ||
| pub enum AddressConversionError { | ||
| NonZeroWordPadding, | ||
| NonZeroBytePrefix, | ||
| InvalidHexLength, | ||
| InvalidHexChar(char), | ||
| HexParseError, | ||
| FeltOutOfField, | ||
| InvalidAccountId, | ||
| } | ||
|
|
||
| impl fmt::Display for AddressConversionError { | ||
| fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { | ||
| match self { | ||
| AddressConversionError::NonZeroWordPadding => write!(f, "non-zero word padding"), | ||
| AddressConversionError::NonZeroBytePrefix => { | ||
| write!(f, "address has non-zero 4-byte prefix") | ||
| }, | ||
| AddressConversionError::InvalidHexLength => { | ||
| write!(f, "invalid hex length (expected 40 hex chars)") | ||
| }, | ||
| AddressConversionError::InvalidHexChar(c) => write!(f, "invalid hex character: {}", c), | ||
| AddressConversionError::HexParseError => write!(f, "hex parse error"), | ||
| AddressConversionError::FeltOutOfField => { | ||
| write!(f, "packed 64-bit word does not fit in the field") | ||
| }, | ||
| AddressConversionError::InvalidAccountId => write!(f, "invalid AccountId"), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| impl From<HexParseError> for AddressConversionError { | ||
| fn from(_err: HexParseError) -> Self { | ||
| AddressConversionError::HexParseError | ||
| } | ||
| } | ||
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For some reason, I had previously thought that Ethereum addresses are natively in little-endian order - but it seems like they are in big-endian order. So, does this mean that to get the address in this form we need to reverse the bytes?
If so, it may be worth going back to the "native" order of Ethereum addresses - i.e.,
addr0 = bytes[0..3].