zaun_community_protocol/signed/
session.rs1use super::error::SessionProofError;
4use super::object::{FORMAT_V1, Signed, SignedObject, read_format};
5use super::validity::ValidPair;
6use crate::crypto::{self, Context};
7use crate::encoding::{Decode, DecodeError, Encode, EncodeError, Reader, Writer};
8use crate::ids::{Challenge, CommunityId, HostId, Nonce};
9use crate::json::SignedJson;
10use crate::keys::PublicKey;
11
12#[derive(Debug, Clone, PartialEq, Eq)]
14pub struct HostSessionProof {
15 pub host_id: HostId,
17 pub client_nonce: Nonce,
19 pub host_challenge: Challenge,
21 pub community_id: Option<CommunityId>,
23 pub delegation_epoch: Option<u64>,
25 pub issued_at: u64,
27}
28
29impl Encode for HostSessionProof {
30 fn encode(&self, w: &mut Writer) -> Result<(), EncodeError> {
31 w.u8(FORMAT_V1);
32 w.put(&self.host_id)?;
33 w.put(&self.client_nonce)?;
34 w.put(&self.host_challenge)?;
35 w.option(self.community_id.as_ref(), Writer::put)?;
36 w.option(self.delegation_epoch.as_ref(), Writer::put)?;
37 w.u64(self.issued_at);
38 Ok(())
39 }
40}
41
42impl Decode for HostSessionProof {
43 fn decode(r: &mut Reader<'_>) -> Result<Self, DecodeError> {
44 read_format(r)?;
45 Ok(Self {
46 host_id: r.get()?,
47 client_nonce: r.get()?,
48 host_challenge: r.get()?,
49 community_id: r.option(Reader::get)?,
50 delegation_epoch: r.option(Reader::get)?,
51 issued_at: r.u64()?,
52 })
53 }
54}
55
56impl SignedObject for HostSessionProof {
57 const CONTEXT: Context = Context::HostSession;
58}
59
60impl HostSessionProof {
61 pub fn verify_for_client(
70 signed: &SignedJson,
71 host_public_key: &PublicKey,
72 client_nonce: &Nonce,
73 pair: Option<&ValidPair>,
74 ) -> Result<Signed<Self>, SessionProofError> {
75 let min_suite = pair.map_or(1, |pair| pair.state().min_suite);
76 let signed = Signed::<Self>::from_json(signed, host_public_key, min_suite)?;
77 let proof = signed.object();
78 if proof.host_id != crypto::host_id(host_public_key) {
79 return Err(SessionProofError::HostId);
80 }
81 if proof.client_nonce != *client_nonce {
82 return Err(SessionProofError::Nonce);
83 }
84 match (proof.community_id, proof.delegation_epoch) {
88 (None, None) => Ok(signed),
89 (Some(community), Some(epoch)) => {
90 let pair = pair.ok_or(SessionProofError::MissingPair)?;
91 let delegation = pair.delegation().object();
92 let matches = pair.descriptor().object().community_id == community
93 && delegation.host_id == proof.host_id
94 && delegation.host_public_key == *host_public_key
95 && delegation.epoch == epoch;
96 if matches {
97 Ok(signed)
98 } else {
99 Err(SessionProofError::PairMismatch)
100 }
101 }
102 _ => Err(SessionProofError::EpochPresence),
103 }
104 }
105}