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,
};
#[derive(Debug, Clone, PartialEq, Eq)]
enum Payload {
Typed(Box<TypedData>),
Text(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Verified {
payload: Payload,
digest: B256,
signer: Address,
not_after: Option<i64>,
}
impl Verified {
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 })
}
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 }
}
pub fn digest(&self) -> B256 {
self.digest
}
pub fn not_after(&self) -> Option<i64> {
self.not_after
}
pub fn signer(&self) -> Address {
self.signer
}
pub fn typed_data(&self) -> Option<&TypedData> {
match &self.payload {
Payload::Typed(typed) => Some(typed),
Payload::Text(_) => None,
}
}
pub fn message(&self) -> Option<&str> {
match &self.payload {
Payload::Typed(_) => None,
Payload::Text(text) => Some(text),
}
}
fn in_time(&self, now: DateTime<Utc>) -> bool {
self.not_after.is_none_or(|limit| now.timestamp() <= limit)
}
}
#[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 {
pub(crate) fn new<S: Signer + Send + Sync + 'static>(signer: S) -> Self {
let address = signer.address();
Self { signer: Arc::new(signer), address }
}
pub(crate) fn address(&self) -> Address {
self.address
}
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;