pub const RESERVED_SELECTORS: [[u8; 4]; 8] = [
[0x1f, 0x93, 0x1c, 0x1c], [0xf2, 0xfd, 0xe3, 0x8b], [0x8d, 0xa5, 0xcb, 0x5b], [0x7a, 0x0e, 0xd6, 0x27], [0xad, 0xfc, 0xa1, 0x5e], [0x52, 0xef, 0x6b, 0x2c], [0xcd, 0xff, 0xac, 0xc6], [0x01, 0xff, 0xc9, 0xa7], ];
fn hex4(s: &[u8; 4]) -> String {
format!("0x{:02x}{:02x}{:02x}{:02x}", s[0], s[1], s[2], s[3])
}
pub fn check_cut(new: &[[u8; 4]], existing: &[[u8; 4]], init_is_zero: bool) -> Result<(), Vec<String>> {
let mut errs = Vec::new();
if !init_is_zero {
errs.push(
"cut `_init` must be address(0): an init delegatecall runs arbitrary code in the \
diamond's storage context (can overwrite owner/credits) — forbidden for agent cuts"
.to_string(),
);
}
for s in new {
if RESERVED_SELECTORS.contains(s) {
errs.push(format!(
"refusing to cut reserved diamond selector {} (cut/ownership/loupe) — a facet must \
not be able to seize the diamond",
hex4(s)
));
}
if existing.contains(s) {
errs.push(format!(
"selector {} already exists on the diamond — an Add cut would revert; remove it \
from the facet or Replace deliberately",
hex4(s)
));
}
}
for (i, s) in new.iter().enumerate() {
if new[i + 1..].contains(s) {
errs.push(format!("selector {} is declared twice in the facet", hex4(s)));
}
}
if errs.is_empty() {
Ok(())
} else {
Err(errs)
}
}
#[cfg(test)]
mod tests {
use super::*;
const A: [u8; 4] = [0xaa, 0xbb, 0xcc, 0xdd];
const B: [u8; 4] = [0x11, 0x22, 0x33, 0x44];
const DIAMOND_CUT: [u8; 4] = [0x1f, 0x93, 0x1c, 0x1c];
const OWNER: [u8; 4] = [0x8d, 0xa5, 0xcb, 0x5b];
#[test]
fn clean_cut_passes() {
assert!(check_cut(&[A, B], &[], true).is_ok());
assert!(check_cut(&[A], &[B], true).is_ok());
}
#[test]
fn clash_is_rejected() {
let e = check_cut(&[A, B], &[B], true).unwrap_err();
assert_eq!(e.len(), 1);
assert!(e[0].contains("already exists"), "{e:?}");
}
#[test]
fn reserved_selectors_are_rejected() {
let e = check_cut(&[DIAMOND_CUT], &[], true).unwrap_err();
assert!(e[0].contains("reserved"), "{e:?}");
assert!(check_cut(&[OWNER], &[], true).is_err());
for s in RESERVED_SELECTORS {
assert!(check_cut(&[s], &[], true).is_err(), "missed reserved {s:?}");
}
}
#[test]
fn nonzero_init_is_rejected() {
let e = check_cut(&[A], &[], false).unwrap_err();
assert!(e.iter().any(|r| r.contains("_init")), "{e:?}");
}
#[test]
fn duplicate_selector_in_facet_is_rejected() {
let e = check_cut(&[A, A], &[], true).unwrap_err();
assert!(e.iter().any(|r| r.contains("twice")), "{e:?}");
}
#[test]
fn all_problems_reported_at_once() {
let e = check_cut(&[DIAMOND_CUT, A], &[A], false).unwrap_err();
assert!(e.len() >= 3, "expected >=3 reasons, got {e:?}");
}
}