use std::io;
use teter_common::command::{
Command, Outcome, Signed, challenge_bytes, command_bytes, command_info, reply_bytes, reply_info,
};
use crate::account::{AccountKeys, seal_to, verify};
#[derive(Debug, Clone)]
pub struct Challenge {
pub nonce: Vec<u8>,
pub key: Vec<u8>,
}
#[must_use]
pub fn check_challenge(
machine: &str,
machine_key: &[u8],
nonce: Vec<u8>,
key: Vec<u8>,
signature: &[u8],
) -> Option<Challenge> {
verify(
machine_key,
&challenge_bytes(machine, &nonce, &key),
signature,
)
.then_some(Challenge { nonce, key })
}
pub fn seal_command(
account: &AccountKeys,
machine: &str,
challenge: &Challenge,
command: Command,
) -> io::Result<Vec<u8>> {
let signature = account.sign(&command_bytes(machine, &challenge.nonce, &command));
let signed = serde_json::to_vec(&Signed { command, signature }).map_err(io::Error::other)?;
seal_to(
&challenge.key,
&command_info(machine, &challenge.nonce),
&signed,
)
}
pub fn open_reply(
account: &AccountKeys,
machine: &str,
machine_key: &[u8],
nonce: &[u8],
sealed: &[u8],
signature: &[u8],
) -> io::Result<Outcome> {
if !verify(machine_key, &reply_bytes(machine, nonce, sealed), signature) {
return Err(io::Error::other("the reply is not signed by the machine"));
}
let plain = account
.open_sealed(&reply_info(machine, nonce), sealed)
.map_err(io::Error::other)?;
serde_json::from_slice(&plain).map_err(io::Error::other)
}