Skip to content
Merged
Show file tree
Hide file tree
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 Jan 9, 2026
3c84da6
fix: formatting
partylikeits1983 Jan 9, 2026
c71d9df
refactor: rm unnecessary indirection
partylikeits1983 Jan 9, 2026
779ab24
refactor: use crypto util functions
partylikeits1983 Jan 9, 2026
a8238b6
refactor: implement suggestions & refactor
partylikeits1983 Jan 9, 2026
5dd9c85
refactor: update logic & comments to little endian
partylikeits1983 Jan 9, 2026
99bcee7
Update crates/miden-agglayer/src/utils.rs
partylikeits1983 Jan 9, 2026
2d0a89a
refactor: improve EthAddress representation clarity and MASM alignment
partylikeits1983 Jan 9, 2026
3d45e7f
refactor: simplify ethereum_address_to_account_id proc
partylikeits1983 Jan 9, 2026
43cbcf3
fix: clippy
partylikeits1983 Jan 9, 2026
049e8be
fix: lint doc check
partylikeits1983 Jan 9, 2026
99161e3
refactor: use u32assert2
partylikeits1983 Jan 9, 2026
3dc29f6
refactor: simplify from_account_id() & u32 check
partylikeits1983 Jan 9, 2026
4c6289d
revert: undo drop addr4 in ethereum_address_to_account_id
partylikeits1983 Jan 9, 2026
a1a1c3d
Update crates/miden-agglayer/src/eth_address.rs
partylikeits1983 Jan 13, 2026
1264d24
refactor: rename to EthAddressFormat
partylikeits1983 Jan 13, 2026
2288c0d
refactor: rearrange EthAddressFormat
partylikeits1983 Jan 13, 2026
d9c309a
refactor: rename file to eth_address_format
partylikeits1983 Jan 13, 2026
393ee03
Merge branch 'agglayer' into ajl-solidity-type-conversions
partylikeits1983 Jan 14, 2026
3c3c29e
fix: update script roots
partylikeits1983 Jan 14, 2026
aac64df
refactor: update test & refactor
partylikeits1983 Jan 14, 2026
888e787
refactor: refactor .to_elements() method
partylikeits1983 Jan 14, 2026
9b7333b
refactor: rename to to_account_id
partylikeits1983 Jan 14, 2026
de94d04
fix: lint check
partylikeits1983 Jan 14, 2026
7abace4
refactor: rename to eth_address.rs & undo Felt::try_from() changes
partylikeits1983 Jan 15, 2026
31b1875
Merge branch 'agglayer' into ajl-solidity-type-conversions
bobbinth Jan 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion crates/miden-agglayer/asm/bridge/crypto_utils.masm
Original file line number Diff line number Diff line change
Expand Up @@ -80,4 +80,3 @@ pub proc verify_claim_proof
dropw dropw dropw dropw
push.1
end

97 changes: 97 additions & 0 deletions crates/miden-agglayer/asm/bridge/eth_address.masm
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.
#! 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
#!
#! 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
# --- 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]

# --- 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
12 changes: 12 additions & 0 deletions crates/miden-agglayer/src/errors/agglayer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ use miden_protocol::errors::MasmError;
// AGGLAYER ERRORS
// ================================================================================================

/// Error Message: "first 4 bytes (addr0) must be zero"
pub const ERR_ADDR0_NONZERO: MasmError = MasmError::from_static_str("first 4 bytes (addr0) must be zero");

/// Error Message: "B2AGG script requires exactly 1 note asset"
pub const ERR_B2AGG_WRONG_NUMBER_OF_ASSETS: MasmError = MasmError::from_static_str("B2AGG script requires exactly 1 note asset");
/// Error Message: "B2AGG script expects exactly 6 note inputs"
Expand All @@ -20,5 +23,14 @@ pub const ERR_CLAIM_TARGET_ACCT_MISMATCH: MasmError = MasmError::from_static_str
/// Error Message: "invalid claim proof"
pub const ERR_INVALID_CLAIM_PROOF: MasmError = MasmError::from_static_str("invalid claim proof");

/// Error Message: "address limb is not u32"
pub const ERR_NOT_U32: MasmError = MasmError::from_static_str("address limb is not u32");

/// Error Message: "prefix would wrap field modulus"
pub const ERR_PREFIX_OUT_OF_FIELD: MasmError = MasmError::from_static_str("prefix would wrap field modulus");

/// Error Message: "maximum scaling factor is 18"
pub const ERR_SCALE_AMOUNT_EXCEEDED_LIMIT: MasmError = MasmError::from_static_str("maximum scaling factor is 18");

/// Error Message: "suffix would wrap field modulus"
pub const ERR_SUFFIX_OUT_OF_FIELD: MasmError = MasmError::from_static_str("suffix would wrap field modulus");
202 changes: 202 additions & 0 deletions crates/miden-agglayer/src/eth_address.rs
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).
///
/// 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]);

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))
}

/// 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.
///
/// # 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> {
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
}

/// 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])];

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
}

// 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> {
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])
}
}

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
}
}
Loading
Loading