lamarge 0.9.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! LaMarge's attestations, checked by a signer that holds a taker's key apart from the app that
//! asks it: the request it is about to sign is the one LaMarge asks, and a take's terms are the
//! ones LaMarge committed to.

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},
};

/// LaMarge's attester addresses of one environment, the newest first; a key rotation lists both
/// until the old one retires.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Attesters {
    /// Production's.
    pub production: &'static [Address],
    /// Development's.
    pub development: &'static [Address],
}

impl Attesters {
    /// `environment`'s attesters.
    pub const fn of(&self, environment: EscrowEnvironment) -> &'static [Address] {
        match environment {
            EscrowEnvironment::Production => self.production,
            EscrowEnvironment::Development => self.development,
        }
    }
}

/// LaMarge's attesters by environment.
pub const ATTESTERS: Attesters = Attesters {
    production: &[address!("4552ab53f861f8990ab504cea09369d4ec5dc787")],
    development: &[address!("f9d52b2ab0912cd972aaf545049e9c86dd74a7e9")],
};

/// What an attestation proves.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Attested {
    /// A take LaMarge commits to `terms`, delivered to `destination`: a wallet's terms name the
    /// wallet token and the least received.
    #[non_exhaustive]
    Take {
        /// The terms, for the signer's own policy: where and how it delivers, how much.
        terms: TakeTerms,
        /// Where the take delivers.
        destination: Destination,
    },
    /// One of LaMarge's own setup steps: its Aster agent, its Lighter key.
    #[non_exhaustive]
    Setup,
}

/// The wallet request about to be signed.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SignRequest {
    /// Typed data as `eth_signTypedData_v4` receives it: exactly `domain`, `types`,
    /// `primaryType` and `message`.
    TypedData(Value),
    /// A `personal_sign` text.
    Message(String),
}

/// Why an attestation is not LaMarge's.
#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
#[error("not attested by LaMarge: {0}")]
pub struct NotAttested(pub &'static str);

/// The attestations' signing domain: no chain, no contract.
fn domain() -> Eip712Domain {
    Eip712Domain::new(
        Some(Cow::Borrowed("LaMarge attestation")),
        Some(Cow::Borrowed("2")),
        None,
        None,
        None,
    )
}

mod statements {
    alloy_sol_types::sol! {
        /// What a venue delivery delivers.
        struct TakeTerms {
            bytes32 take;
            string from;
            string to;
            address recipient;
            address token;
            uint256 amountOut;
            uint64 payBy;
        }

        /// A take's request, attested with its terms.
        struct TakeAttestation {
            address signer;
            bytes32 digest;
            TakeTerms terms;
        }

        /// What a wallet delivery delivers: the venue terms and `destination` "wallet".
        struct WalletTakeTerms {
            bytes32 take;
            string from;
            string to;
            address recipient;
            address token;
            uint256 amountOut;
            uint64 payBy;
            string destination;
        }

        /// A wallet take's request, attested with its terms.
        struct WalletTakeAttestation {
            address signer;
            bytes32 digest;
            WalletTakeTerms terms;
        }

        /// A setup step's request.
        struct SetupAttestation {
            address signer;
            bytes32 digest;
        }
    }
}

/// Half the secp256k1 order: a signature with a higher `s` is the malleated twin of another.
const HALF_ORDER: [u8; 32] =
    alloy_primitives::hex!("7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0");

/// The hash the wallet signs for `request`, computed here: never one the caller or the API
/// supplies.
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) => {
            // Exactly the four keys: a wallet given more may sign what was not checked.
            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);
            }
            // The wallet builds the domain separator from the declared `EIP712Domain`; the digest
            // here from `domain`. They agree only when the declared type is the canonical one.
            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)
        }
    }
}

/// The `EIP712Domain` type of `domain`'s fields, in EIP-712's order, as a wallet derives it.
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(),
    )
}

/// A take's terms as the attester signed them, and where the take delivers: a wallet
/// delivery's carry `destination` `"wallet"` as an eighth field.
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"))?;
    // A JSON integer, as a JavaScript safe integer.
    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 },
    })
}

/// Whether LaMarge's attester, one of `attesters` (`ATTESTERS.production`, or a local server's
/// own), asks `address` (the trusted key's own address) to sign `request`, the exact request
/// about to be signed. A take's attestation also authenticates its terms, returned with its
/// destination for the signer's own policy, and is refused from `payBy` on. It proves where a
/// request comes from, never that it should be signed: it fails whenever it is not LaMarge's.
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,
    })
}

/// `r ‖ s ‖ v` in 130 hex digits, `v` 27 or 28 and `s` in the lower half: one encoding per
/// signature.
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);
    }
    // Big-endian and of equal length: compared bytewise, compared as numbers.
    if bytes[32..64] > HALF_ORDER[..] {
        return Err(NotAttested("a high-s signature"));
    }
    Signature::from_raw(&bytes).map_err(|_| BAD)
}

#[cfg(test)]
mod tests;