use alloc::string::String;
use alloc::vec::Vec;
use paperpaw_sdk::Storage;
use paperpaw_sdk::native::keys::{self, MAX_REVOKED, Revocation};
use paperpaw_sdk::native::known_author;
const MAX_READ: usize = 4096;
#[derive(Default)]
pub(crate) struct Revocations {
plugin: String,
key: String,
signature: String,
pending: Vec<Revocation>,
kept: Option<Vec<String>>,
read: usize,
}
impl Revocations {
pub(crate) fn field(&mut self, field: &str, value: &str) {
let (to, most) = match field {
"plugin" => (&mut self.plugin, 64),
"key" => (&mut self.key, 64),
"signature" => (&mut self.signature, 128),
_ => return,
};
*to = value.chars().take(most + 1).collect();
}
pub(crate) fn entry_done(&mut self, storage: &dyn Storage, here: &dyn Fn(&str) -> bool) {
let entry = (
bytes::<32>(&self.key),
bytes::<64>(&self.signature),
core::mem::take(&mut self.plugin),
);
self.key.clear();
self.signature.clear();
self.read += 1;
let (Some(key), Some(signature), plugin) = entry else {
return;
};
if self.read > MAX_READ
|| self.pending.len() >= MAX_REVOKED
|| plugin.is_empty()
|| !here(&plugin)
|| known_author(storage, &plugin) != Some(key)
|| self.pending.iter().any(|r| r.plugin == plugin)
{
return;
}
let kept = self.kept.get_or_insert_with(|| {
keys::revoked(storage)
.into_iter()
.map(|r| r.plugin)
.collect()
});
if !kept.contains(&plugin) {
self.pending.push(Revocation::new(plugin, key, signature));
}
}
pub(crate) fn hand_over(&mut self, storage: &dyn Storage) {
if !self.pending.is_empty() {
let _ = keys::keep_revoked(storage, &self.pending);
self.pending.clear();
}
}
}
fn bytes<const N: usize>(hex: &str) -> Option<[u8; N]> {
paperpaw_sdk::digest::hex::decode(hex)?.try_into().ok()
}