use crate::enc::{Enc, signed_by};
use crate::ids::ProjectId;
use crate::records::SignError;
use serde::{Deserialize, Serialize};
use weirdnet_contacts::UserId;
use weirdnet_net::Keypair;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub enum HandoverKind {
Leave,
Standby,
}
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Handover {
pub project: ProjectId,
pub from: UserId,
pub to: UserId,
pub kind: HandoverKind,
pub at_ms: i64,
pub key: Vec<u8>,
pub sig: Vec<u8>,
}
impl Handover {
fn bytes(&self) -> Vec<u8> {
Enc::new("handover")
.s(self.project.as_str())
.s(self.from.as_str())
.s(self.to.as_str())
.u8(match self.kind {
HandoverKind::Leave => 0,
HandoverKind::Standby => 1,
})
.i64(self.at_ms)
.b(&self.key)
.done()
}
pub(crate) fn sign(host: &Keypair, project: &ProjectId, to: &UserId, kind: HandoverKind, now: i64) -> Result<Handover, SignError> {
let mut h = Handover {
project: project.clone(),
from: UserId::of_keypair(host),
to: to.clone(),
kind,
at_ms: now,
key: host.public().encode_protobuf(),
sig: Vec::new(),
};
h.sig = host.sign(&h.bytes()).map_err(|e| SignError(e.to_string()))?;
Ok(h)
}
pub fn verify(&self) -> bool {
signed_by(&self.from, &self.key, &self.bytes(), &self.sig)
}
}