use std::{fmt, future::Future};
use serde::{Deserialize, Deserializer, Serialize};
use crate::error::{Error, ValidationError};
use super::{Preparation, PreparedRequest};
#[derive(Clone, Eq, PartialEq, Serialize)]
#[serde(transparent)]
pub struct HandoffId(String);
impl HandoffId {
pub const MAX_BYTES: usize = 128;
pub fn new(value: &str) -> Result<Self, Error> {
if value.is_empty()
|| value.len() > Self::MAX_BYTES
|| !value
.bytes()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_'))
{
return Err(ValidationError::InvalidWalletHandoffId.into());
}
Ok(Self(value.into()))
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl fmt::Debug for HandoffId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandoffId").finish_non_exhaustive()
}
}
impl<'de> Deserialize<'de> for HandoffId {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
Self::new(&String::deserialize(d)?).map_err(serde::de::Error::custom)
}
}
#[derive(Clone, Eq, PartialEq, Serialize)]
pub struct HandoffRequest<P: Preparation> {
id: HandoffId,
prepared: PreparedRequest<P>,
}
impl<P: Preparation> HandoffRequest<P> {
#[must_use]
pub const fn new(id: HandoffId, prepared: PreparedRequest<P>) -> Self {
Self { id, prepared }
}
#[must_use]
pub const fn id(&self) -> &HandoffId {
&self.id
}
#[must_use]
pub const fn prepared(&self) -> &PreparedRequest<P> {
&self.prepared
}
}
impl<P: Preparation> fmt::Debug for HandoffRequest<P> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandoffRequest").finish_non_exhaustive()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct RequestFields<P> {
id: HandoffId,
prepared: P,
}
impl<'de, P: Preparation + Deserialize<'de>> Deserialize<'de> for HandoffRequest<P> {
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let fields = RequestFields::<PreparedRequest<P>>::deserialize(d)?;
Ok(Self::new(fields.id, fields.prepared))
}
}
#[derive(Clone, Eq, PartialEq, Serialize)]
pub struct HandoffResponse<P: Preparation, S> {
id: HandoffId,
prepared: PreparedRequest<P>,
signed: S,
}
impl<P: Preparation, S> HandoffResponse<P, S> {
#[must_use]
pub const fn new(id: HandoffId, prepared: PreparedRequest<P>, signed: S) -> Self {
Self {
id,
prepared,
signed,
}
}
#[must_use]
pub const fn id(&self) -> &HandoffId {
&self.id
}
#[must_use]
pub const fn prepared(&self) -> &PreparedRequest<P> {
&self.prepared
}
#[must_use]
pub const fn signed(&self) -> &S {
&self.signed
}
}
impl<P: Preparation, S> fmt::Debug for HandoffResponse<P, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("HandoffResponse").finish_non_exhaustive()
}
}
#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct ResponseFields<P, S> {
id: HandoffId,
prepared: P,
signed: S,
}
impl<'de, P: Preparation + Deserialize<'de>, S: Deserialize<'de>> Deserialize<'de>
for HandoffResponse<P, S>
{
fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let fields = ResponseFields::<PreparedRequest<P>, S>::deserialize(d)?;
Ok(Self::new(fields.id, fields.prepared, fields.signed))
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VerificationDecision {
Confirmed,
Rejected,
}
pub trait SignedPayloadVerifier<P: Preparation, S> {
fn verify_binding(
&self,
prepared: &PreparedRequest<P>,
signed: &S,
) -> impl Future<Output = Result<VerificationDecision, Error>> + crate::future::MaybeSend;
}
#[derive(Clone)]
pub struct VerifiedSignedPayload<P: Preparation, S> {
id: HandoffId,
prepared: PreparedRequest<P>,
signed: S,
}
impl<P: Preparation, S> VerifiedSignedPayload<P, S> {
#[must_use]
pub const fn id(&self) -> &HandoffId {
&self.id
}
#[must_use]
pub const fn prepared(&self) -> &PreparedRequest<P> {
&self.prepared
}
#[must_use]
pub const fn signed(&self) -> &S {
&self.signed
}
#[must_use]
pub fn into_signed(self) -> S {
self.signed
}
}
impl<P: Preparation, S> fmt::Debug for VerifiedSignedPayload<P, S> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("VerifiedSignedPayload")
.finish_non_exhaustive()
}
}
pub async fn verify_handoff<P: Preparation, S, V: SignedPayloadVerifier<P, S>>(
request: &HandoffRequest<P>,
response: HandoffResponse<P, S>,
verifier: &V,
) -> Result<VerifiedSignedPayload<P, S>, Error> {
if request.id != response.id || !request.prepared.matches(&response.prepared) {
return Err(ValidationError::WalletBindingMismatch.into());
}
match verifier
.verify_binding(&request.prepared, &response.signed)
.await?
{
VerificationDecision::Rejected => Err(ValidationError::SignedPayloadRejected.into()),
VerificationDecision::Confirmed => Ok(VerifiedSignedPayload {
id: request.id.clone(),
prepared: request.prepared.clone(),
signed: response.signed,
}),
}
}