1use std::io;
7
8use teter_common::command::{
9 Command, Outcome, Signed, challenge_bytes, command_bytes, command_info, reply_bytes, reply_info,
10};
11
12use crate::account::{AccountKeys, seal_to, verify};
13
14#[derive(Debug, Clone)]
16pub struct Challenge {
17 pub nonce: Vec<u8>,
19 pub key: Vec<u8>,
21}
22
23#[must_use]
26pub fn check_challenge(
27 machine: &str,
28 machine_key: &[u8],
29 nonce: Vec<u8>,
30 key: Vec<u8>,
31 signature: &[u8],
32) -> Option<Challenge> {
33 verify(
34 machine_key,
35 &challenge_bytes(machine, &nonce, &key),
36 signature,
37 )
38 .then_some(Challenge { nonce, key })
39}
40
41pub fn seal_command(
48 account: &AccountKeys,
49 machine: &str,
50 challenge: &Challenge,
51 command: Command,
52) -> io::Result<Vec<u8>> {
53 let signature = account.sign(&command_bytes(machine, &challenge.nonce, &command));
54 let signed = serde_json::to_vec(&Signed { command, signature }).map_err(io::Error::other)?;
55 seal_to(
56 &challenge.key,
57 &command_info(machine, &challenge.nonce),
58 &signed,
59 )
60}
61
62pub fn open_reply(
70 account: &AccountKeys,
71 machine: &str,
72 machine_key: &[u8],
73 nonce: &[u8],
74 sealed: &[u8],
75 signature: &[u8],
76) -> io::Result<Outcome> {
77 if !verify(machine_key, &reply_bytes(machine, nonce, sealed), signature) {
78 return Err(io::Error::other("the reply is not signed by the machine"));
79 }
80 let plain = account
81 .open_sealed(&reply_info(machine, nonce), sealed)
82 .map_err(io::Error::other)?;
83 serde_json::from_slice(&plain).map_err(io::Error::other)
84}