use std::borrow::Cow;
use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, B256, Signature, U256, address, eip191_hash_message};
use alloy_sol_types::{Eip712Domain, SolStruct};
use chrono::{DateTime, Utc};
use serde_json::{Map, Value};
use crate::{
model::{Destination, TakeTerms},
protocol::eip712,
types::{Amount, EscrowEnvironment, VenueId},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Attesters {
pub production: &'static [Address],
pub development: &'static [Address],
}
impl Attesters {
pub const fn of(&self, environment: EscrowEnvironment) -> &'static [Address] {
match environment {
EscrowEnvironment::Production => self.production,
EscrowEnvironment::Development => self.development,
}
}
}
pub const ATTESTERS: Attesters = Attesters {
production: &[address!("4552ab53f861f8990ab504cea09369d4ec5dc787")],
development: &[address!("f9d52b2ab0912cd972aaf545049e9c86dd74a7e9")],
};
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attested {
#[non_exhaustive]
Take {
terms: TakeTerms,
destination: Destination,
},
#[non_exhaustive]
Setup,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignRequest {
TypedData(Value),
Message(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("not attested by LaMarge: {0}")]
pub struct NotAttested(pub &'static str);
fn domain() -> Eip712Domain {
Eip712Domain::new(
Some(Cow::Borrowed("LaMarge attestation")),
Some(Cow::Borrowed("2")),
None,
None,
None,
)
}
mod statements {
alloy_sol_types::sol! {
struct TakeTerms {
bytes32 take;
string from;
string to;
address recipient;
address token;
uint256 amountOut;
uint64 payBy;
}
struct TakeAttestation {
address signer;
bytes32 digest;
TakeTerms terms;
}
struct WalletTakeTerms {
bytes32 take;
string from;
string to;
address recipient;
address token;
uint256 amountOut;
uint64 payBy;
string destination;
}
struct WalletTakeAttestation {
address signer;
bytes32 digest;
WalletTakeTerms terms;
}
struct SetupAttestation {
address signer;
bytes32 digest;
}
}
}
const HALF_ORDER: [u8; 32] =
alloy_primitives::hex!("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0");
pub fn request_digest(request: &SignRequest) -> Result<B256, NotAttested> {
const NEITHER: NotAttested = NotAttested("the request is neither typed data nor a message");
match request {
SignRequest::Message(text) => Ok(eip191_hash_message(text.as_bytes())),
SignRequest::TypedData(value) => {
let fields = value.as_object().ok_or(NEITHER)?;
let keys = ["domain", "types", "primaryType", "message"];
let shaped = fields.len() == keys.len()
&& keys.iter().all(|key| fields.contains_key(*key))
&& fields["domain"].is_object()
&& fields["types"].is_object()
&& fields["primaryType"].is_string()
&& fields["message"].is_object();
if !shaped {
return Err(NEITHER);
}
if let Some(declared) = fields["types"].get("EIP712Domain")
&& *declared != domain_type(&fields["domain"])
{
return Err(NotAttested("the request's EIP712Domain differs from its domain"));
}
let typed: TypedData = serde_json::from_value(value.clone()).map_err(|_| NEITHER)?;
typed.eip712_signing_hash().map_err(|_| NEITHER)
}
}
}
fn domain_type(domain: &Value) -> Value {
let fields = [
("name", "string"),
("version", "string"),
("chainId", "uint256"),
("verifyingContract", "address"),
("salt", "bytes32"),
];
Value::Array(
fields
.into_iter()
.filter(|(name, _)| domain.get(name).is_some())
.map(|(name, kind)| serde_json::json!({"name": name, "type": kind}))
.collect(),
)
}
struct Terms {
take: B256,
from: String,
to: String,
recipient: Address,
token: Address,
amount_out: U256,
pay_by: u64,
destination: Destination,
}
fn terms(value: &Value) -> Result<Terms, NotAttested> {
const KEYS: [&str; 7] = ["take", "from", "to", "recipient", "token", "amountOut", "payBy"];
let fields: &Map<String, Value> = value.as_object().ok_or(NotAttested("no take terms"))?;
let wallet = fields.contains_key("destination");
if (wallet && fields["destination"] != "wallet")
|| fields.len() != KEYS.len() + usize::from(wallet)
|| !KEYS.iter().all(|key| fields.contains_key(*key))
{
return Err(NotAttested("unexpected take terms"));
}
let text = |name: &str| fields[name].as_str().unwrap_or_default();
let take = text("take");
if !(take.len() == 66 && take.starts_with("0x")) {
return Err(NotAttested("take id"));
}
let take: B256 = take.parse().map_err(|_| NotAttested("take id"))?;
let (from, to) = (text("from"), text("to"));
if from.is_empty() || to.is_empty() {
return Err(NotAttested("venues"));
}
let recipient = eip712::address_text(text("recipient"));
let token = eip712::address_text(text("token"));
let (Some(recipient), Some(token)) = (recipient, token) else {
return Err(NotAttested("recipient or token"));
};
let amount = text("amountOut");
let canonical = amount == "0"
|| (!amount.is_empty()
&& !amount.starts_with('0')
&& amount.bytes().all(|b| b.is_ascii_digit()));
let amount_out = canonical
.then(|| U256::from_str_radix(amount, 10).ok())
.flatten()
.ok_or(NotAttested("amount"))?;
let pay_by =
fields["payBy"].as_u64().filter(|pay_by| *pay_by < 1 << 53).ok_or(NotAttested("payBy"))?;
Ok(Terms {
take,
from: from.to_owned(),
to: to.to_owned(),
recipient,
token,
amount_out,
pay_by,
destination: if wallet { Destination::Wallet } else { Destination::Venue },
})
}
pub fn verify_attestation(
request: &SignRequest,
address: Address,
attestation: &Value,
attesters: &[Address],
now: DateTime<Utc>,
) -> Result<Attested, NotAttested> {
if attesters.is_empty() {
return Err(NotAttested("no attester pinned"));
}
let fields = attestation.as_object().ok_or(NotAttested("no attestation"))?;
if fields.keys().any(|key| key != "signature" && key != "terms") {
return Err(NotAttested("unexpected attestation fields"));
}
let signature = signature(fields.get("signature"))?;
let digest = request_digest(request)?;
let take = fields.get("terms").map(terms).transpose()?;
let domain = domain();
let hash = match &take {
None => {
statements::SetupAttestation { signer: address, digest }.eip712_signing_hash(&domain)
}
Some(t) if t.destination == Destination::Wallet => statements::WalletTakeAttestation {
signer: address,
digest,
terms: statements::WalletTakeTerms {
take: t.take,
from: t.from.clone(),
to: t.to.clone(),
recipient: t.recipient,
token: t.token,
amountOut: t.amount_out,
payBy: t.pay_by,
destination: "wallet".to_owned(),
},
}
.eip712_signing_hash(&domain),
Some(t) => statements::TakeAttestation {
signer: address,
digest,
terms: statements::TakeTerms {
take: t.take,
from: t.from.clone(),
to: t.to.clone(),
recipient: t.recipient,
token: t.token,
amountOut: t.amount_out,
payBy: t.pay_by,
},
}
.eip712_signing_hash(&domain),
};
let recovered =
signature.recover_address_from_prehash(&hash).map_err(|_| NotAttested("signature"))?;
if !attesters.contains(&recovered) {
return Err(NotAttested("another key signed it"));
}
let Some(t) = take else { return Ok(Attested::Setup) };
if now.timestamp() >= i64::try_from(t.pay_by).unwrap_or(i64::MAX) {
return Err(NotAttested("its payment window closed"));
}
let venue = |name: String| name.parse::<VenueId>().unwrap_or_else(|never| match never {});
Ok(Attested::Take {
terms: TakeTerms {
take: t.take,
from: venue(t.from),
to: venue(t.to),
recipient: t.recipient,
token: t.token,
amount_out: Amount::new(t.amount_out),
pay_by: t.pay_by,
},
destination: t.destination,
})
}
fn signature(value: Option<&Value>) -> Result<Signature, NotAttested> {
const BAD: NotAttested = NotAttested("signature");
let text = value.and_then(Value::as_str).ok_or(BAD)?;
let digits = text.strip_prefix("0x").filter(|digits| digits.len() == 130).ok_or(BAD)?;
let bytes: [u8; 65] = alloy_primitives::hex::decode_to_array(digits).map_err(|_| BAD)?;
if !matches!(bytes[64], 27 | 28) {
return Err(BAD);
}
if bytes[32..64] > HALF_ORDER[..] {
return Err(NotAttested("a high-s signature"));
}
Signature::from_raw(&bytes).map_err(|_| BAD)
}
#[cfg(test)]
mod tests;