Skip to content
Merged
Show file tree
Hide file tree
Changes from 33 commits
Commits
Show all changes
35 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
a5f3309
Merge branch 'ajl-solidity-type-conversions' into ajl-agglayer-get-le…
partylikeits1983 Jan 12, 2026
576f907
feat: init getLeafValue() test
partylikeits1983 Jan 12, 2026
a8e35d3
feat: implement AdviceMap key based getLeafValue procedure
partylikeits1983 Jan 12, 2026
a1a1c3d
Update crates/miden-agglayer/src/eth_address.rs
partylikeits1983 Jan 13, 2026
359b3ef
refactor: update test name
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
a926316
Merge branch 'ajl-solidity-type-conversions' into ajl-agglayer-get-le…
mmagician Jan 14, 2026
af29827
chore: pipe words to memory
mmagician Jan 14, 2026
d6b9954
refactor: add stack comments
partylikeits1983 Jan 14, 2026
f9f2d57
chore: pipe words to memory instead of manual `adv_loadw`
partylikeits1983 Jan 14, 2026
d61f836
refactor: deduplicate execute_program_with_default_host
partylikeits1983 Jan 14, 2026
d51bed1
feat: add hardcoded expected hash to test
partylikeits1983 Jan 14, 2026
1388770
fix: verify hash matches commitment
mmagician Jan 15, 2026
f200752
fix: put data under correct key in advice map
mmagician Jan 15, 2026
8ebdc7b
chore: merge agglayer
partylikeits1983 Jan 19, 2026
1567d89
fix: rm redundant file
partylikeits1983 Jan 20, 2026
c1aec4d
Merge branch 'agglayer' into ajl-agglayer-get-leaf-value
partylikeits1983 Jan 21, 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: 1 addition & 1 deletion crates/miden-agglayer/asm/bridge/bridge_in.masm
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ end
#! Invocation: call
pub proc check_claim_proof
exec.get_rollup_exit_root
# => [GER_ROOT[8], CLAIM_NOTE_RPO_COMMITMENT]
# => [GER_ROOT[8], PROOF_DATA_KEY, LEAF_DATA_KEY]

# Check CLAIM note proof data against current GER
exec.crypto_utils::verify_claim_proof
Expand Down
1 change: 0 additions & 1 deletion crates/miden-agglayer/asm/bridge/bridge_out.masm
Original file line number Diff line number Diff line change
Expand Up @@ -157,4 +157,3 @@ pub proc bridge_out
exec.create_burn_note
# => []
end

55 changes: 33 additions & 22 deletions crates/miden-agglayer/asm/bridge/crypto_utils.masm
Original file line number Diff line number Diff line change
@@ -1,32 +1,43 @@
use miden::core::crypto::hashes::keccak256
use miden::core::mem

#! Given the leaf data returns the leaf value.
const LEAF_DATA_BYTES = 113
const LEAF_DATA_NUM_WORDS = 8
const LEAF_DATA_START_PTR = 0

#! Given the leaf data key returns the leaf value.
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: might have been good to explain somewhere (briefly) that LFEAF_VALUE is just a sequential hash of LEAF_DATA using `Keccak hash function.

#!
#! Inputs: [leaf_type, origin_network, ORIGIN_ADDRESS, destination_network, DESTINATION_ADDRESS, amount, METADATA_HASH]
#! Inputs:
#! Operand stack: [LEAF_DATA_KEY]
#! Advice map: {
#! LEAF_DATA_KEY => [
#! originNetwork[1], // Origin network identifier (1 felt, uint32)
#! originTokenAddress[5], // Origin token address (5 felts, address as 5 u32 felts)
#! destinationNetwork[1], // Destination network identifier (1 felt, uint32)
#! destinationAddress[5], // Destination address (5 felts, address as 5 u32 felts)
#! amount[8], // Amount of tokens (8 felts, uint256 as 8 u32 felts)
#! metadata[8], // ABI encoded metadata (8 felts, fixed size)
#! ],
#! }
#! Outputs: [LEAF_VALUE]
#!
#! Where:
#! - leaf_type is the leaf type: [0] transfer Ether / ERC20 tokens, [1] message.
#! - origin_network is the origin network identifier.
#! - ORIGIN_ADDRESS is the origin token address (5 elements)
#! - destination_network is the destination network identifier.
#! - DESTINATION_ADDRESS is the destination address (5 elements).
#! - amount is the amount: [0] Amount of tokens/ether, [1] Amount of ether.
#! - METADATA_HASH is the hash of the metadata (8 elements).
#! - LEAF_VALUE is the computed leaf value (8 elements).
#!
#! This function computes the keccak256 hash of the abi.encodePacked data.
#!
#! Invocation: exec
pub proc get_leaf_value
# TODO: implement getLeafValue()
# https://github.com/agglayer/agglayer-contracts/blob/e468f9b0967334403069aa650d9f1164b1731ebb/contracts/v2/lib/DepositContractV2.sol#L22
adv.push_mapval
# => [LEAF_DATA_KEY]

# stubbed out:
push.1.1.1.1
push.1.1.1.1

# exec.keccak256::hash_bytes
push.LEAF_DATA_START_PTR push.LEAF_DATA_NUM_WORDS
exec.mem::pipe_preimage_to_memory drop
# => []

push.LEAF_DATA_BYTES push.LEAF_DATA_START_PTR
# => [start_ptr, byte_len]

exec.keccak256::hash_bytes
# => [LEAF_VALUE[8]]

# truncate stack
swapdw dropw dropw
# => [LEAF_VALUE[8]]
end

Expand All @@ -36,7 +47,7 @@ end
#! and that the leaf has not been previously claimed.
#!
#! Inputs:
#! Operand stack: [GER_ROOT[8], CLAIM_PROOF_RPO_COMMITMENT, pad(12)]
#! Operand stack: [GER_ROOT[8], PROOF_DATA_KEY, LEAF_DATA_KEY, pad(12)]
#! Advice map: {
#! PROOF_DATA_KEY => [
#! smtProofLocalExitRoot[256], // SMT proof for local exit root (256 felts, bytes32[_DEPOSIT_CONTRACT_TREE_DEPTH])
Expand Down
242 changes: 242 additions & 0 deletions crates/miden-agglayer/src/eth_address_format.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,242 @@
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};

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum AddrConvError {
NonZeroWordPadding,
NonZeroBytePrefix,
InvalidHexLength,
InvalidHexChar(char),
HexParseError,
FeltOutOfField,
InvalidAccountId,
}

impl fmt::Display for AddrConvError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
AddrConvError::NonZeroWordPadding => write!(f, "non-zero word padding"),
AddrConvError::NonZeroBytePrefix => write!(f, "address has non-zero 4-byte prefix"),
AddrConvError::InvalidHexLength => {
write!(f, "invalid hex length (expected 40 hex chars)")
},
AddrConvError::InvalidHexChar(c) => write!(f, "invalid hex character: {}", c),
AddrConvError::HexParseError => write!(f, "hex parse error"),
AddrConvError::FeltOutOfField => {
write!(f, "packed 64-bit word does not fit in the field")
},
AddrConvError::InvalidAccountId => write!(f, "invalid AccountId"),
}
}
}

impl From<HexParseError> for AddrConvError {
fn from(_err: HexParseError) -> Self {
AddrConvError::HexParseError
}
}

// ================================================================================================
// 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, AddrConvError> {
let hex_part = hex_str.strip_prefix("0x").unwrap_or(hex_str);
if hex_part.len() != 40 {
return Err(AddrConvError::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 {
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
/// `ethereum_address_format_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 (i, felt) in result.iter_mut().enumerate() {
let start = (4 - 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 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 `ethereum_address_format_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, AddrConvError> {
let (prefix, suffix) = Self::bytes20_to_prefix_suffix(self.0)?;

// `Felt::new(u64)` may reduce mod p for some u64 values. Mirror the MASM `build_felt`
// safety: construct the felt, then require round-trip equality.
let prefix_felt = Felt::new(prefix);
if prefix_felt.as_int() != prefix {
return Err(AddrConvError::FeltOutOfField);
}

let suffix_felt = Felt::new(suffix);
if suffix_felt.as_int() != suffix {
return Err(AddrConvError::FeltOutOfField);
}

AccountId::try_from([prefix_felt, suffix_felt]).map_err(|_| AddrConvError::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), AddrConvError> {
if bytes[0..4] != [0, 0, 0, 0] {
return Err(AddrConvError::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
}
}
Loading