use std::borrow::Borrow;
use std::collections::btree_map::Entry;
use std::collections::BTreeMap;
use std::time::Duration;
use bytes::Bytes;
use rings_core::consts::DEFAULT_TTL_MS;
use rings_core::consts::TS_OFFSET_TOLERANCE_MS;
use rings_core::delegation::DelegateeKey;
use rings_core::dht::entry::Entry as DhtEntry;
use rings_core::dht::Did;
use rings_core::ecc::VerificationPublicKey;
use rings_core::error::Error;
use rings_core::error::Result;
use rings_core::message::DomainTag;
use rings_core::message::MessageSigner;
use rings_core::message::MessageVerification;
use rings_core::message::SigningDomain;
use serde::de::DeserializeOwned;
use serde::Serialize;
pub trait SignedDescriptorBody: Sized {
type Descriptor;
const DOMAIN_TAG: DomainTag;
fn body_did(&self) -> Did;
fn body_public_key(&self) -> &VerificationPublicKey;
fn body_network_id(&self) -> u32;
fn body_signing_data(&self) -> Result<Vec<u8>>;
fn into_signed_descriptor(self, signature: MessageVerification) -> Self::Descriptor;
}
pub const fn registry_lease() -> Duration {
Duration::from_millis(DEFAULT_TTL_MS)
}
pub fn sign_descriptor_body<B>(
body: B,
signer: MessageSigner<impl Borrow<DelegateeKey>>,
mismatch_message: &'static str,
) -> Result<B::Descriptor>
where
B: SignedDescriptorBody,
{
let did = body.body_did();
if body.body_public_key().did() != did || signer.delegator_did() != did {
return Err(Error::InvalidMessage(mismatch_message.to_string()));
}
if body.body_network_id() != signer.network_id() {
return Err(Error::InvalidMessage(
"descriptor states an overlay other than the signer's".to_string(),
));
}
let signature = signer.sign(B::DOMAIN_TAG, &body.body_signing_data()?)?;
Ok(body.into_signed_descriptor(signature))
}
pub trait SignedDescriptor: Sized {
type Body: SignedDescriptorBody<Descriptor = Self>;
fn descriptor_did(&self) -> Did;
fn descriptor_public_key(&self) -> &VerificationPublicKey;
fn descriptor_network_id(&self) -> u32;
fn descriptor_signature(&self) -> &MessageVerification;
fn descriptor_heartbeat_at_ms(&self) -> u128;
fn descriptor_expires_at_ms(&self) -> u128;
fn descriptor_fresh_for_ms(&self) -> u64;
fn descriptor_signing_data(&self) -> Result<Vec<u8>>;
fn heard_at(self, heartbeat_at_ms: u128) -> Self;
fn descriptor_verify_signature(&self, network_id: u32) -> bool {
self.descriptor_verify_signature_at(network_id, rings_core::utils::get_epoch_ms())
}
fn descriptor_verify_signature_at(&self, network_id: u32, at_ms: u128) -> bool {
if self.descriptor_network_id() != network_id {
return false;
}
let did = self.descriptor_did();
let public_key = self.descriptor_public_key();
let signature = self.descriptor_signature();
if public_key.did() != did || signature.delegation.delegator_did() != did {
return false;
}
let Ok(delegatee_public_key) = signature.delegation.delegator_verification_pubkey() else {
return false;
};
if &delegatee_public_key != public_key {
return false;
}
let Ok(data) = self.descriptor_signing_data() else {
return false;
};
let domain =
SigningDomain::new(<Self::Body as SignedDescriptorBody>::DOMAIN_TAG, network_id);
signature.verify_at(domain, &data, at_ms)
}
fn descriptor_live_until_ms(&self) -> u128 {
let heard_until = self
.descriptor_heartbeat_at_ms()
.saturating_add(u128::from(self.descriptor_fresh_for_ms()))
.saturating_add(TS_OFFSET_TOLERANCE_MS);
self.descriptor_expires_at_ms().min(heard_until)
}
fn descriptor_is_expired_at(&self, now_ms: u128) -> bool {
self.descriptor_live_until_ms() < now_ms
}
fn descriptor_terms_admissible_at(&self, now_ms: u128) -> bool {
let lease_ms = registry_lease().as_millis();
self.descriptor_expires_at_ms()
<= now_ms
.saturating_add(lease_ms)
.saturating_add(TS_OFFSET_TOLERANCE_MS)
&& u128::from(self.descriptor_fresh_for_ms()) <= lease_ms
}
fn descriptor_is_live_at(&self, now_ms: u128, network_id: u32) -> bool {
self.descriptor_verify_signature_at(network_id, now_ms)
&& self.descriptor_terms_admissible_at(now_ms)
&& !self.descriptor_is_expired_at(now_ms)
}
fn supersedes(&self, other: &Self) -> bool {
let rank = |descriptor: &Self| {
(
descriptor.descriptor_expires_at_ms(),
descriptor.descriptor_heartbeat_at_ms(),
)
};
let content = |descriptor: &Self| {
Some((
descriptor.descriptor_signing_data().ok()?,
rings_codec::serialize(descriptor.descriptor_signature()).ok()?,
))
};
rank(self)
.cmp(&rank(other))
.then_with(|| content(self).cmp(&content(other)))
== std::cmp::Ordering::Greater
}
}
pub fn latest_valid_by_did<D>(
descriptors: impl IntoIterator<Item = D>,
now_ms: u128,
network_id: u32,
include_expired: bool,
) -> Vec<D>
where
D: SignedDescriptor,
{
latest_valid_by_key(
descriptors,
SignedDescriptor::descriptor_did,
now_ms,
network_id,
include_expired,
)
.into_values()
.collect()
}
pub fn latest_valid_by_key<K, D>(
descriptors: impl IntoIterator<Item = D>,
key: impl Fn(&D) -> K,
now_ms: u128,
network_id: u32,
include_expired: bool,
) -> BTreeMap<K, D>
where
K: Ord,
D: SignedDescriptor,
{
let mut latest = BTreeMap::<K, D>::new();
for descriptor in descriptors {
if include_expired {
if !descriptor.descriptor_verify_signature_at(network_id, now_ms) {
continue;
}
} else if !descriptor.descriptor_is_live_at(now_ms, network_id) {
continue;
}
match latest.entry(key(&descriptor)) {
Entry::Occupied(mut entry) => {
if descriptor.supersedes(entry.get()) {
entry.insert(descriptor);
}
}
Entry::Vacant(entry) => {
entry.insert(descriptor);
}
}
}
latest
}
pub trait RegistryElement: Serialize + DeserializeOwned {
fn to_element(&self) -> Result<Bytes> {
rings_codec::serialize(self)
.map(Bytes::from)
.map_err(Error::CodecSerialize)
}
fn from_element(element: &[u8]) -> Result<Self> {
rings_codec::deserialize(element).map_err(Error::CodecDeserialize)
}
}
pub fn heard_elements(entry: &DhtEntry) -> impl Iterator<Item = (&Bytes, u128)> {
entry.data.iter().zip(
entry
.crdt
.dots
.iter()
.map(|dot| dot.version.logical_time_ms),
)
}
pub fn heard_descriptors<D>(entry: &DhtEntry) -> Vec<D>
where D: SignedDescriptor + RegistryElement {
heard_elements(entry)
.filter_map(|(element, heard_at_ms)| {
D::from_element(element)
.ok()
.map(|descriptor| descriptor.heard_at(heard_at_ms))
})
.collect()
}