lamarge 0.5.1

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
//! The signing key: signs only payloads the checkers verified.
//!
//! Flows hold a [`SigningKey`], never the raw signer, and its only signing method takes a
//! [`Verified`], which only `crate::protocol` constructs after its checks. The signed payload is
//! the one the checks rebuilt; a signature is refused past the checks' `not_after`, and must
//! recover to the key's address.

use std::{fmt, sync::Arc};

use alloy_dyn_abi::TypedData;
use alloy_primitives::{Address, B256, eip191_hash_message};
use alloy_signer::Signer;
use chrono::{DateTime, Utc};

use super::checks::details::{self, differs, stale};
use crate::{
    error::{Error, SignerError, VerificationError},
    transport::Clock,
    types::SignatureBytes,
};

/// What a [`Verified`] asks the signer to sign.
#[derive(Debug, Clone, PartialEq, Eq)]
enum Payload {
    /// EIP-712 typed data, rebuilt from checked terms and pinned domains.
    Typed(Box<TypedData>),
    /// An EIP-191 `personal_sign` text.
    Text(String),
}

/// A payload the checks verified for `signer`, signable until `not_after` (Unix seconds).
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Verified {
    payload: Payload,
    digest: B256,
    signer: Address,
    not_after: Option<i64>,
}

impl Verified {
    /// Typed data the checks rebuilt; refused unless it hashes to the server's `server_digest`.
    pub(in crate::protocol) fn typed(
        rebuilt: TypedData,
        server_digest: B256,
        signer: Address,
        not_after: Option<i64>,
    ) -> Result<Self, VerificationError> {
        let digest = rebuilt.eip712_signing_hash().map_err(|_| differs(details::DIGEST))?;
        if digest != server_digest {
            return Err(differs(details::DIGEST));
        }
        Ok(Self { payload: Payload::Typed(Box::new(rebuilt)), digest, signer, not_after })
    }

    /// A text the checks rebuilt or matched exactly.
    pub(in crate::protocol) fn text(
        message: String,
        signer: Address,
        not_after: Option<i64>,
    ) -> Self {
        let digest = eip191_hash_message(message.as_bytes());
        Self { payload: Payload::Text(message), digest, signer, not_after }
    }

    /// The hash the signature signs: the EIP-712 digest or the EIP-191 hash.
    pub(crate) fn digest(&self) -> B256 {
        self.digest
    }

    /// The latest moment, in Unix seconds, the checks allow signing.
    #[cfg(test)]
    pub(crate) fn not_after(&self) -> Option<i64> {
        self.not_after
    }

    fn in_time(&self, now: DateTime<Utc>) -> bool {
        self.not_after.is_none_or(|limit| now.timestamp() <= limit)
    }
}

/// A signer that signs only [`Verified`] payloads.
#[derive(Clone)]
pub(crate) struct SigningKey {
    signer: Arc<dyn Signer + Send + Sync>,
    address: Address,
}

impl fmt::Debug for SigningKey {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("SigningKey").field("address", &self.address).finish_non_exhaustive()
    }
}

impl SigningKey {
    /// Wraps `signer`, whose address is read once.
    pub(crate) fn new<S: Signer + Send + Sync + 'static>(signer: S) -> Self {
        let address = signer.address();
        Self { signer: Arc::new(signer), address }
    }

    /// The signer's address.
    pub(crate) fn address(&self) -> Address {
        self.address
    }

    /// Signs `verified`: refused unless it names this key and the clock is not past its
    /// `not_after`, checked again once the signer returns (a slow hardware or remote signer);
    /// the signature must recover to this key. Returns `r ‖ s ‖ v`, low `s`, `v` 27 or 28.
    pub(crate) async fn sign(
        &self,
        verified: &Verified,
        clock: &Clock,
    ) -> Result<SignatureBytes, Error> {
        if verified.signer != self.address {
            return Err(differs(details::SIGNER).into());
        }
        if !verified.in_time(clock()) {
            return Err(stale(details::SIGNING_WINDOW).into());
        }
        let signed = match &verified.payload {
            Payload::Typed(typed) => self.signer.sign_dynamic_typed_data(typed).await,
            Payload::Text(text) => self.signer.sign_message(text.as_bytes()).await,
        }
        .map_err(signer_failed)?;
        if !verified.in_time(clock()) {
            return Err(stale(details::SIGNING_WINDOW).into());
        }
        let signature = signed.normalize_s().unwrap_or(signed);
        let recovered = signature
            .recover_address_from_prehash(&verified.digest)
            .map_err(|error| signer_failed(error.into()))?;
        if recovered != self.address {
            return Err(Error::Signer(Box::new(SignerError::Mismatch {
                expected: self.address,
                recovered,
            })));
        }
        SignatureBytes::new(signature.as_bytes()).ok_or_else(|| {
            signer_failed(alloy_signer::Error::message("signature v is not 27 or 28"))
        })
    }
}

fn signer_failed(error: alloy_signer::Error) -> Error {
    Error::Signer(Box::new(SignerError::Failed(error)))
}

#[cfg(test)]
mod tests;