lamarge 0.6.0

Client for the LaMarge API: sign-in, takes, transfers, withdrawals and market making, each request checked before it is signed.
Documentation
use std::{
    future::Future,
    path::{Path, PathBuf},
    pin::Pin,
    sync::atomic::{AtomicI64, AtomicUsize, Ordering},
};

use alloy_primitives::{ChainId, Signature, U256, address};
use alloy_signer::SignerSync;
use alloy_signer_local::PrivateKeySigner;

use super::*;
use crate::{
    error::VerificationKind,
    protocol::eip712::{self, Permit},
    testing::NOW,
};

/// A signer that counts its calls, may sign with another key than it claims, may take
/// `delay` seconds of the test clock, and may return the high-`s` twin of its signature.
struct Scripted {
    key: PrivateKeySigner,
    claims: Address,
    calls: Arc<AtomicUsize>,
    clock: Arc<AtomicI64>,
    delay: i64,
    high_s: bool,
}

impl Signer for Scripted {
    fn sign_hash<'life0, 'life1, 'async_trait>(
        &'life0 self,
        hash: &'life1 B256,
    ) -> Pin<Box<dyn Future<Output = alloy_signer::Result<Signature>> + Send + 'async_trait>>
    where
        'life0: 'async_trait,
        'life1: 'async_trait,
        Self: 'async_trait,
    {
        Box::pin(async move {
            self.calls.fetch_add(1, Ordering::SeqCst);
            self.clock.fetch_add(self.delay, Ordering::SeqCst);
            let low = self.key.sign_hash_sync(hash)?;
            if !self.high_s {
                return Ok(low);
            }
            let order = U256::from_be_bytes(alloy_primitives::hex!(
                "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141"
            ));
            Ok(Signature::new(low.r(), order - low.s(), !low.v()))
        })
    }

    fn address(&self) -> Address {
        self.claims
    }

    fn chain_id(&self) -> Option<ChainId> {
        None
    }

    fn set_chain_id(&mut self, _: Option<ChainId>) {}
}

struct Harness {
    key: SigningKey,
    address: Address,
    calls: Arc<AtomicUsize>,
    clock: Clock,
}

fn harness(other_key: bool, delay: i64, high_s: bool) -> Harness {
    let real = PrivateKeySigner::random();
    let address = real.address();
    let key = if other_key { PrivateKeySigner::random() } else { real };
    let calls = Arc::new(AtomicUsize::new(0));
    let time = Arc::new(AtomicI64::new(NOW));
    let signer =
        Scripted { key, claims: address, calls: calls.clone(), clock: time.clone(), delay, high_s };
    let clock: Clock =
        Arc::new(move || DateTime::from_timestamp(time.load(Ordering::SeqCst), 0).unwrap());
    Harness { key: SigningKey::new(signer), address, calls, clock }
}

fn permit(owner: Address) -> TypedData {
    let message = Permit {
        owner,
        spender: address!("3100b7b49c0f9631c6af25877b5a4e13a47afad6"),
        value: U256::MAX,
        nonce: U256::ZERO,
        deadline: U256::from(NOW + 600),
    };
    eip712::typed(&message, eip712::domain("USDC", "2", 999, Some(Address::ZERO)))
}

fn typed(owner: Address, not_after: Option<i64>) -> Verified {
    let payload = permit(owner);
    let digest = payload.eip712_signing_hash().unwrap();
    Verified::typed(payload, digest, owner, not_after).unwrap()
}

fn refusal(error: Error) -> (VerificationKind, &'static str) {
    match error {
        Error::Verification(error) => (error.kind, error.detail),
        other => unreachable!("not a verification error: {other:?}"),
    }
}

#[tokio::test]
async fn signs_typed_data_and_text_recoverably_with_v_27_or_28() {
    let h = harness(false, 0, false);
    assert_eq!(h.key.address(), h.address);
    for verified in [typed(h.address, None), Verified::text("hello".to_owned(), h.address, None)] {
        let signature = h.key.sign(&verified, &h.clock).await.unwrap();
        let bytes = signature.as_bytes();
        assert!(matches!(bytes[64], 27 | 28));
        let parsed = Signature::from_raw(bytes).unwrap();
        assert_eq!(parsed.recover_address_from_prehash(&verified.digest()).unwrap(), h.address);
        assert!(parsed.normalize_s().is_none(), "s is low");
    }
    assert_eq!(h.calls.load(Ordering::SeqCst), 2);
    assert_eq!(
        Verified::text("hello".to_owned(), h.address, None).digest(),
        eip191_hash_message("hello")
    );
}

#[tokio::test]
async fn refuses_a_payload_for_another_signer_without_calling_the_signer() {
    let h = harness(false, 0, false);
    let other = address!("1111111111111111111111111111111111111111");
    let error = h.key.sign(&typed(other, None), &h.clock).await.unwrap_err();
    assert_eq!(refusal(error), (VerificationKind::Differs, details::SIGNER));
    assert_eq!(h.calls.load(Ordering::SeqCst), 0);
}

#[tokio::test]
async fn refuses_past_not_after_without_calling_the_signer() {
    let h = harness(false, 0, false);
    let limit = NOW;
    assert!(h.key.sign(&typed(h.address, Some(limit)), &h.clock).await.is_ok());
    let error = h.key.sign(&typed(h.address, Some(limit - 1)), &h.clock).await.unwrap_err();
    assert_eq!(refusal(error), (VerificationKind::Stale, details::SIGNING_WINDOW));
    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn a_signer_finishing_past_not_after_gives_no_signature() {
    let h = harness(false, 5, false);
    let limit = NOW + 4;
    let error = h.key.sign(&typed(h.address, Some(limit)), &h.clock).await.unwrap_err();
    assert_eq!(refusal(error), (VerificationKind::Stale, details::SIGNING_WINDOW));
    assert_eq!(h.calls.load(Ordering::SeqCst), 1);
}

#[tokio::test]
async fn a_signature_from_another_key_is_a_mismatch() {
    let h = harness(true, 0, false);
    let error = h.key.sign(&typed(h.address, None), &h.clock).await.unwrap_err();
    match error {
        Error::Signer(error) => match *error {
            SignerError::Mismatch { expected, recovered } => {
                assert_eq!(expected, h.address);
                assert_ne!(recovered, h.address);
            }
            SignerError::Failed(error) => unreachable!("{error}"),
        },
        other => unreachable!("{other:?}"),
    }
}

#[test]
fn a_rebuilt_payload_must_hash_to_the_servers_digest() {
    let owner = address!("1111111111111111111111111111111111111111");
    let error = Verified::typed(permit(owner), B256::ZERO, owner, None).unwrap_err();
    assert_eq!((error.kind, error.detail), (VerificationKind::Differs, details::DIGEST));
}

/// A high-`s` signature is normalised (the server and the escrow require low `s`).
#[tokio::test]
async fn high_s_signatures_are_normalised() {
    let h = harness(false, 0, true);
    let verified = typed(h.address, None);
    let signature = h.key.sign(&verified, &h.clock).await.unwrap();
    let parsed = Signature::from_raw(signature.as_bytes()).unwrap();
    assert!(parsed.normalize_s().is_none());
    assert_eq!(parsed.recover_address_from_prehash(&verified.digest()).unwrap(), h.address);
}

/// Only this module calls a signer's raw signing methods.
#[test]
fn raw_signer_calls_live_only_in_the_signing_module() {
    fn visit(dir: &Path, offenders: &mut Vec<PathBuf>) {
        for entry in std::fs::read_dir(dir).unwrap() {
            let path = entry.unwrap().path();
            if path.is_dir() {
                visit(&path, offenders);
            } else if path.extension().is_some_and(|ext| ext == "rs")
                && !path.ends_with("protocol/signing.rs")
                && !path.ends_with("protocol/signing/tests.rs")
            {
                let text = std::fs::read_to_string(&path).unwrap();
                let calls = [
                    ".sign_hash(",
                    ".sign_message(",
                    ".sign_dynamic_typed_data(",
                    ".sign_typed_data(",
                    "sign_hash_sync(",
                    "sign_message_sync(",
                    "sign_typed_data_sync(",
                    "sign_dynamic_typed_data_sync(",
                ];
                if calls.iter().any(|call| text.contains(call)) {
                    offenders.push(path);
                }
            }
        }
    }
    let mut offenders = Vec::new();
    visit(&Path::new(env!("CARGO_MANIFEST_DIR")).join("src"), &mut offenders);
    assert!(offenders.is_empty(), "raw signer calls outside protocol/signing.rs: {offenders:?}");
}