ensip25 0.4.1

Rust implementation of ENSIP-25: verify the link between ENS names and ERC-8004 AI agent registries.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! ERC-7930 Interoperable Address encoding and decoding.
//!
//! [ERC-7930](https://eips.ethereum.org/EIPS/eip-7930) defines a compact binary
//! format that binds a chain identifier and an address into a single payload.
//!
//! This module provides [`InteropAddress`] for constructing, encoding, decoding,
//! and displaying interoperable addresses — the building block for ENSIP-25
//! text record keys.
//!
//! # Wire format
//!
//! ```text
//! ┌─────────┬───────────┬──────────────────────┬────────────────┬───────────────┬─────────┐
//! │ Version │ ChainType │ ChainReferenceLength │ ChainReference │ AddressLength │ Address │
//! │ 2 bytes │ 2 bytes   │ 1 byte               │ variable       │ 1 byte        │ variable│
//! └─────────┴───────────┴──────────────────────┴────────────────┴───────────────┴─────────┘
//! ```

use core::fmt;

use alloy_primitives::{Address, hex};

use crate::error::{Ensip25Error, Result};

/// Current ERC-7930 version.
const VERSION_1: u16 = 0x0001;

/// CASA namespace for EVM chains.
const CHAIN_TYPE_EVM: u16 = 0x0000;

/// An ERC-7930 interoperable address.
///
/// Represents a chain-specific address in the compact binary format defined by
/// the specification. Use [`InteropAddress::evm`] for the common EVM case or
/// [`InteropAddress::decode`] to parse raw bytes.
#[derive(Clone, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct InteropAddress {
    version: u16,
    chain_type: u16,
    chain_ref: Vec<u8>,
    address: Vec<u8>,
}

impl InteropAddress {
    /// Create an EVM interoperable address for the given chain ID and address.
    ///
    /// The chain ID is encoded as a minimal big-endian integer (no leading
    /// zero bytes), matching the ERC-7930 / CAIP-350 EVM profile.
    ///
    /// # Examples
    ///
    /// ```
    /// use ensip25::erc7930::InteropAddress;
    /// use alloy_primitives::address;
    ///
    /// let ia = InteropAddress::evm(1, address!("8004A169FB4a3325136EB29fA0ceB6D2e539a432"));
    /// assert!(ia.is_evm());
    /// assert_eq!(ia.evm_chain_id(), Some(1));
    /// ```
    #[must_use]
    pub fn evm(chain_id: u64, address: Address) -> Self {
        Self {
            version: VERSION_1,
            chain_type: CHAIN_TYPE_EVM,
            chain_ref: minimal_be_bytes(chain_id),
            address: address.to_vec(),
        }
    }

    /// Create an EVM interoperable address **without** a chain reference.
    ///
    /// This is valid per ERC-7930 (chain reference length = 0).
    #[must_use]
    pub fn evm_no_chain(address: Address) -> Self {
        Self {
            version: VERSION_1,
            chain_type: CHAIN_TYPE_EVM,
            chain_ref: Vec::new(),
            address: address.to_vec(),
        }
    }

    /// Returns the protocol version.
    #[must_use]
    pub const fn version(&self) -> u16 {
        self.version
    }

    /// Returns the CASA namespace identifier (e.g. `0x0000` for EVM).
    #[must_use]
    pub const fn chain_type(&self) -> u16 {
        self.chain_type
    }

    /// Returns the binary chain reference bytes.
    #[must_use]
    pub fn chain_ref(&self) -> &[u8] {
        &self.chain_ref
    }

    /// Returns the binary address bytes.
    #[must_use]
    pub fn address_bytes(&self) -> &[u8] {
        &self.address
    }

    /// Decode an interoperable address from raw bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if the buffer is malformed or uses an unsupported
    /// version.
    pub fn decode(bytes: &[u8]) -> Result<Self> {
        // Minimum: version(2) + chain_type(2) + chain_ref_len(1) + addr_len(1) = 6
        let header: &[u8; 6] = bytes
            .get(..6)
            .and_then(|s| s.try_into().ok())
            .ok_or(Ensip25Error::BufferTooShort { len: bytes.len() })?;

        let version = u16::from_be_bytes([header[0], header[1]]);
        if version != VERSION_1 {
            return Err(Ensip25Error::UnsupportedVersion { version });
        }

        let chain_type = u16::from_be_bytes([header[2], header[3]]);
        let chain_ref_len = header[4] as usize;

        let addr_len_offset = 5 + chain_ref_len;
        let &addr_len_byte = bytes
            .get(addr_len_offset)
            .ok_or(Ensip25Error::TruncatedPayload {
                expected: addr_len_offset + 1,
                available: bytes.len(),
            })?;
        let addr_len = addr_len_byte as usize;

        let total = addr_len_offset + 1 + addr_len;
        if bytes.len() < total {
            return Err(Ensip25Error::TruncatedPayload {
                expected: total,
                available: bytes.len(),
            });
        }

        if chain_ref_len == 0 && addr_len == 0 {
            return Err(Ensip25Error::EmptyAddress);
        }

        let chain_ref = bytes
            .get(5..5 + chain_ref_len)
            .ok_or(Ensip25Error::TruncatedPayload {
                expected: 5 + chain_ref_len,
                available: bytes.len(),
            })?
            .to_vec();
        let address = bytes
            .get(addr_len_offset + 1..total)
            .ok_or(Ensip25Error::TruncatedPayload {
                expected: total,
                available: bytes.len(),
            })?
            .to_vec();

        Ok(Self {
            version,
            chain_type,
            chain_ref,
            address,
        })
    }

    /// Decode an interoperable address from a hex string (with or without
    /// `0x` prefix).
    ///
    /// # Errors
    ///
    /// Returns an error if the hex is invalid or the payload is malformed.
    pub fn from_hex(s: &str) -> Result<Self> {
        let bytes: Vec<u8> = hex::decode(s)?;
        Self::decode(&bytes)
    }

    /// Encode this interoperable address to raw bytes.
    ///
    /// # Errors
    ///
    /// Returns [`Ensip25Error::FieldTooLong`] if `chain_ref` or `address`
    /// length exceeds 255 bytes.
    pub fn encode(&self) -> Result<Vec<u8>> {
        let chain_ref_len =
            u8::try_from(self.chain_ref.len()).map_err(|_| Ensip25Error::FieldTooLong {
                field: "chain_ref",
                len: self.chain_ref.len(),
            })?;
        let addr_len =
            u8::try_from(self.address.len()).map_err(|_| Ensip25Error::FieldTooLong {
                field: "address",
                len: self.address.len(),
            })?;

        let mut buf = Vec::with_capacity(6 + usize::from(chain_ref_len) + usize::from(addr_len));
        buf.extend_from_slice(&self.version.to_be_bytes());
        buf.extend_from_slice(&self.chain_type.to_be_bytes());
        buf.push(chain_ref_len);
        buf.extend_from_slice(&self.chain_ref);
        buf.push(addr_len);
        buf.extend_from_slice(&self.address);

        Ok(buf)
    }

    /// Format as a lowercase hex string **with** `0x` prefix.
    ///
    /// # Errors
    ///
    /// Returns an error if encoding fails (field length exceeds 255).
    pub fn to_hex(&self) -> Result<String> {
        Ok(format!("0x{}", hex::encode(self.encode()?)))
    }

    /// Returns `true` if this is an EVM-type address (chain type `0x0000`).
    ///
    /// # Examples
    ///
    /// ```
    /// use ensip25::erc7930::InteropAddress;
    /// use alloy_primitives::address;
    ///
    /// let ia = InteropAddress::evm(1, address!("8004A169FB4a3325136EB29fA0ceB6D2e539a432"));
    /// assert!(ia.is_evm());
    /// ```
    #[must_use]
    pub const fn is_evm(&self) -> bool {
        self.chain_type == CHAIN_TYPE_EVM
    }

    /// Try to extract the EVM chain ID from the chain reference.
    ///
    /// Returns `None` if the chain reference is empty or longer than 8 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use ensip25::erc7930::InteropAddress;
    /// use alloy_primitives::address;
    ///
    /// let ia = InteropAddress::evm(1, address!("8004A169FB4a3325136EB29fA0ceB6D2e539a432"));
    /// assert_eq!(ia.evm_chain_id(), Some(1));
    /// ```
    #[must_use]
    pub fn evm_chain_id(&self) -> Option<u64> {
        if self.chain_ref.is_empty() || self.chain_ref.len() > 8 {
            return None;
        }
        let mut padded = [0u8; 8];
        let offset = 8 - self.chain_ref.len();
        padded.get_mut(offset..)?.copy_from_slice(&self.chain_ref);
        Some(u64::from_be_bytes(padded))
    }

    /// Try to extract the 20-byte EVM address.
    ///
    /// Returns `None` if the address is not exactly 20 bytes.
    ///
    /// # Examples
    ///
    /// ```
    /// use ensip25::erc7930::InteropAddress;
    /// use alloy_primitives::address;
    ///
    /// let addr = address!("8004A169FB4a3325136EB29fA0ceB6D2e539a432");
    /// let ia = InteropAddress::evm(1, addr);
    /// assert_eq!(ia.evm_address(), Some(addr));
    /// ```
    #[must_use]
    pub fn evm_address(&self) -> Option<Address> {
        if self.address.len() == 20 {
            Some(Address::from_slice(&self.address))
        } else {
            None
        }
    }
}

impl fmt::Debug for InteropAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("InteropAddress")
            .field("version", &format_args!("{:#06x}", self.version))
            .field("chain_type", &format_args!("{:#06x}", self.chain_type))
            .field("chain_ref", &hex::encode(&self.chain_ref))
            .field("address", &hex::encode(&self.address))
            .finish()
    }
}

impl fmt::Display for InteropAddress {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let bytes = self.encode().map_err(|_| fmt::Error)?;
        f.write_str("0x")?;
        for b in bytes {
            write!(f, "{b:02x}")?;
        }
        Ok(())
    }
}

impl core::str::FromStr for InteropAddress {
    type Err = Ensip25Error;

    fn from_str(s: &str) -> Result<Self> {
        Self::from_hex(s)
    }
}

impl TryFrom<&[u8]> for InteropAddress {
    type Error = Ensip25Error;

    fn try_from(bytes: &[u8]) -> Result<Self> {
        Self::decode(bytes)
    }
}

/// Encode a `u64` as minimal big-endian bytes (no leading zeros).
fn minimal_be_bytes(value: u64) -> Vec<u8> {
    if value == 0 {
        return vec![0];
    }
    let bytes = value.to_be_bytes();
    let skip = bytes.iter().position(|&b| b != 0).unwrap_or(0);
    bytes.get(skip..).map_or_else(|| vec![0], <[u8]>::to_vec)
}

#[cfg(test)]
mod tests {
    use super::*;

    /// ERC-7930 Example 1: Ethereum mainnet address (chain ID 1).
    ///
    /// ```text
    /// 0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432
    /// ```
    #[test]
    fn encode_evm_mainnet() {
        let addr: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid address");
        let ia = InteropAddress::evm(1, addr);
        assert_eq!(
            ia.to_hex().expect("encode ok"),
            "0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432"
        );
    }

    /// ERC-7930 Example 3: EVM address without chain reference.
    ///
    /// ```text
    /// 0x000100000014d8da6bf26964af9d7eed9e03e53415d37aa96045
    /// ```
    #[test]
    fn encode_evm_no_chain() {
        let addr: Address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
            .parse()
            .expect("valid address");
        let ia = InteropAddress::evm_no_chain(addr);
        assert_eq!(
            ia.to_hex().expect("encode ok"),
            "0x000100000014d8da6bf26964af9d7eed9e03e53415d37aa96045"
        );
    }

    /// Roundtrip: encode → decode → encode produces identical output.
    #[test]
    fn roundtrip() {
        let addr: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid address");
        let original = InteropAddress::evm(1, addr);
        let bytes = original.encode().expect("encode ok");
        let decoded = InteropAddress::decode(&bytes).expect("decode ok");
        assert_eq!(original, decoded);
        assert_eq!(
            original.to_hex().expect("encode ok"),
            decoded.to_hex().expect("encode ok")
        );
    }

    /// Decode from hex string (with 0x prefix).
    #[test]
    fn from_hex_with_prefix() {
        let ia =
            InteropAddress::from_hex("0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432")
                .expect("decode ok");
        assert_eq!(ia.version(), 0x0001);
        assert_eq!(ia.chain_type(), 0x0000);
        assert_eq!(ia.evm_chain_id(), Some(1));
        assert_eq!(
            ia.evm_address(),
            Some(
                "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
                    .parse()
                    .expect("valid")
            )
        );
    }

    /// `FromStr` trait works.
    #[test]
    fn from_str() {
        let ia: InteropAddress = "0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432"
            .parse()
            .expect("parse ok");
        assert!(ia.is_evm());
    }

    /// Display produces the same hex as `to_hex`.
    #[test]
    fn display() {
        let addr: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid address");
        let ia = InteropAddress::evm(1, addr);
        assert_eq!(format!("{ia}"), ia.to_hex().expect("encode ok"));
    }

    /// Too-short buffer is rejected.
    #[test]
    fn decode_too_short() {
        assert!(InteropAddress::decode(&[0, 1, 0]).is_err());
    }

    /// Unsupported version is rejected.
    #[test]
    fn decode_unsupported_version() {
        let err = InteropAddress::decode(&[0, 2, 0, 0, 0, 1, 0xFF]).unwrap_err();
        assert!(err.to_string().contains("unsupported version"));
    }

    /// Both lengths zero is rejected.
    #[test]
    fn decode_empty_address() {
        // version=1, chain_type=0, chain_ref_len=0, addr_len=0
        let err = InteropAddress::decode(&[0, 1, 0, 0, 0, 0]).unwrap_err();
        assert!(err.to_string().contains("empty"));
    }

    /// ENSIP-25 example: ERC-8004 `IdentityRegistry` on Ethereum mainnet.
    ///
    /// The spec says the text record key for agent 167 should use:
    /// `0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432`
    #[test]
    fn ensip25_example_registry() {
        let registry: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid");
        let ia = InteropAddress::evm(1, registry);
        assert_eq!(
            ia.to_hex().expect("encode ok"),
            "0x000100000101148004a169fb4a3325136eb29fa0ceb6d2e539a432"
        );
    }

    /// Minimal BE encoding for various chain IDs.
    #[test]
    fn minimal_be_encoding() {
        assert_eq!(minimal_be_bytes(0), vec![0]);
        assert_eq!(minimal_be_bytes(1), vec![1]);
        assert_eq!(minimal_be_bytes(255), vec![255]);
        assert_eq!(minimal_be_bytes(256), vec![1, 0]);
        assert_eq!(minimal_be_bytes(11_155_111), vec![0xAA, 0x36, 0xA7]);
    }

    /// `TryFrom<&[u8]>` delegates to `decode`.
    #[test]
    fn try_from_bytes() {
        let addr: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid address");
        let original = InteropAddress::evm(1, addr);
        let bytes = original.encode().expect("encode ok");
        let decoded = InteropAddress::try_from(bytes.as_slice()).expect("decode ok");
        assert_eq!(original, decoded);
    }

    /// `evm_no_chain` produces `None` for `evm_chain_id`.
    #[test]
    fn evm_no_chain_accessors() {
        let addr: Address = "0xd8dA6BF26964aF9D7eEd9e03E53415D37aA96045"
            .parse()
            .expect("valid address");
        let ia = InteropAddress::evm_no_chain(addr);
        assert!(ia.is_evm());
        assert_eq!(ia.evm_chain_id(), None);
        assert_eq!(ia.evm_address(), Some(addr));
        assert!(ia.chain_ref().is_empty());
    }

    /// Truncated payload (`chain_ref` declared but missing).
    #[test]
    fn decode_truncated_chain_ref() {
        // version=1, chain_type=0, chain_ref_len=5, but only 0 bytes follow
        let err = InteropAddress::decode(&[0, 1, 0, 0, 5, 0]).unwrap_err();
        assert!(err.to_string().contains("truncated"));
    }

    /// Large chain ID roundtrips correctly.
    #[test]
    fn large_chain_id_roundtrip() {
        let addr: Address = "0x8004A169FB4a3325136EB29fA0ceB6D2e539a432"
            .parse()
            .expect("valid address");
        let ia = InteropAddress::evm(u64::MAX, addr);
        let bytes = ia.encode().expect("encode ok");
        let decoded = InteropAddress::decode(&bytes).expect("decode ok");
        assert_eq!(decoded.evm_chain_id(), Some(u64::MAX));
    }
}