use crate::core::{Error, RawTime};
use std::time::Duration;
use p256::ecdsa::VerifyingKey;
use rand::{distr::Alphanumeric, Rng};
use reqwest::blocking::Client;
pub struct Trustime {
service_url: String,
verifying_key: VerifyingKey,
client: Client,
}
impl Trustime {
pub fn new(service_url: impl Into<String>, verifying_key: VerifyingKey) -> Self {
Self {
service_url: service_url.into(),
verifying_key,
client: Client::new(),
}
}
pub fn now(&self) -> Result<Duration, Error> {
let nonce = rand::rng()
.sample_iter(Alphanumeric)
.take(16)
.map(char::from)
.collect::<String>();
Ok(
self.client.get(&self.service_url)
.query(&[("nonce", &nonce)])
.send()?
.json::<RawTime>()?
.digest(&nonce, &self.verifying_key)?
)
}
}