#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
use alloc::collections::BTreeMap;
use alloc::string::String;
use core::cell::UnsafeCell;
use core::marker::PhantomData;
use core::ops::{Deref, DerefMut};
use core::sync::atomic::{AtomicU8, Ordering};
#[derive(Debug, PartialEq, Eq, Clone, Copy)]
#[repr(u8)]
pub enum SovereignState {
Domestic = 0,
Exiled = 1,
}
pub struct RepatriationToken {
_private: (),
}
impl RepatriationToken {
pub unsafe fn new() -> Self {
Self { _private: () }
}
}
pub struct Sovereign<T> {
inner: UnsafeCell<T>,
state: AtomicU8,
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum ConstitutionError {
#[error("Invariant violated: {expression}. Values: {values:?}")]
InvariantViolation {
expression: String,
values: BTreeMap<String, String>,
},
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum SovereigntyError {
#[error("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.")]
ForeignJurisdiction,
}
impl<T> Sovereign<T> {
#[must_use = "Sovereign resources must be managed carefully"]
pub fn new(value: T) -> Self {
Self {
inner: UnsafeCell::new(value),
state: AtomicU8::new(SovereignState::Domestic as u8),
}
}
#[must_use = "Sovereign resources must be managed carefully"]
pub fn new_exiled(value: T) -> Self {
Self {
inner: UnsafeCell::new(value),
state: AtomicU8::new(SovereignState::Exiled as u8),
}
}
#[must_use = "Annexation result should be checked"]
pub fn annex(&self) -> Result<(), AnnexError> {
let current = self.state.load(Ordering::SeqCst);
if current == SovereignState::Exiled as u8 {
return Err(AnnexError::AlreadyExiled);
}
self.state
.store(SovereignState::Exiled as u8, Ordering::SeqCst);
tracing::debug!(
from = "Domestic",
to = "Exiled",
"Resource annexed to foreign jurisdiction"
);
Ok(())
}
pub fn inner_ref(&self) -> &T {
unsafe { &*self.inner.get() }
}
#[inline]
pub fn state(&self) -> SovereignState {
match self.state.load(Ordering::SeqCst) {
0 => SovereignState::Domestic,
_ => SovereignState::Exiled,
}
}
#[inline]
pub fn is_domestic(&self) -> bool {
self.state.load(Ordering::SeqCst) == SovereignState::Domestic as u8
}
#[inline]
pub fn is_exiled(&self) -> bool {
self.state.load(Ordering::SeqCst) == SovereignState::Exiled as u8
}
#[must_use = "Check jurisdiction result"]
pub fn try_get(&self) -> Result<&T, SovereigntyError> {
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
unsafe { Ok(&*self.inner.get()) }
}
#[must_use = "Check jurisdiction result"]
pub fn try_get_mut(&mut self) -> Result<&mut T, SovereigntyError> {
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
unsafe { Ok(&mut *self.inner.get()) }
}
#[must_use = "Ensure resource is actually repatriated"]
pub fn repatriate(&self, _token: RepatriationToken) {
let previous = self
.state
.swap(SovereignState::Domestic as u8, Ordering::SeqCst);
if previous == SovereignState::Exiled as u8 {
tracing::debug!(
from = "Exiled",
to = "Domestic",
"Resource repatriated to domestic jurisdiction"
);
}
}
fn verify_jurisdiction(&self) {
if self.is_exiled() {
panic!("SOVEREIGNTY VIOLATION: Resource is under foreign jurisdiction.");
}
}
pub fn map<F, U>(&self, f: F) -> Result<U, SovereigntyError>
where
F: FnOnce(&T) -> U,
{
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
Ok(f(unsafe { &*self.inner.get() }))
}
pub fn and_then<F, U>(&self, f: F) -> Result<U, SovereigntyError>
where
F: FnOnce(&T) -> Result<U, SovereigntyError>,
{
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
f(unsafe { &*self.inner.get() })
}
pub fn filter<P>(&self, predicate: P) -> Result<Option<&T>, SovereigntyError>
where
P: FnOnce(&T) -> bool,
{
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
let val = unsafe { &*self.inner.get() };
if predicate(val) {
Ok(Some(val))
} else {
Ok(None)
}
}
pub fn modify<F>(&mut self, f: F) -> Result<(), SovereigntyError>
where
F: FnOnce(&mut T),
{
if self.is_exiled() {
return Err(SovereigntyError::ForeignJurisdiction);
}
f(unsafe { &mut *self.inner.get() });
Ok(())
}
}
impl<T> Deref for Sovereign<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.verify_jurisdiction();
unsafe { &*self.inner.get() }
}
}
impl<T> DerefMut for Sovereign<T> {
fn deref_mut(&mut self) -> &mut Self::Target {
self.verify_jurisdiction();
unsafe { &mut *self.inner.get() }
}
}
unsafe impl<T: Send> Send for Sovereign<T> {}
unsafe impl<T: Sync> Sync for Sovereign<T> {}
pub trait CheckProtocol {
fn enforce_law(&self) -> Result<(), ConstitutionError>;
}
#[derive(Debug)]
pub struct ProofCarrying<T> {
pub value: T,
_proof: PhantomData<()>,
}
impl<T> ProofCarrying<T> {
#[doc(hidden)]
pub fn new_unchecked(value: T) -> Self {
Self {
value,
_proof: PhantomData,
}
}
pub fn into_inner(self) -> T {
self.value
}
}
impl<T: Clone> Clone for ProofCarrying<T> {
fn clone(&self) -> Self {
Self {
value: self.value.clone(),
_proof: PhantomData,
}
}
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum AnnexError {
#[error("Resource is already under foreign jurisdiction")]
AlreadyExiled,
#[error("Verification failed: {0}")]
VerificationFailed(String),
#[error("Prover error: {0}")]
ProverError(String),
}
#[derive(thiserror::Error, Debug, Clone, PartialEq, Eq)]
pub enum LeaseError {
#[error("Resource is already leased to another holder")]
AlreadyLeased,
#[error("Resource is under foreign jurisdiction")]
ForeignJurisdiction,
#[error("Lease duration must be non-zero")]
InvalidDuration,
}
pub struct Lease<T> {
pub holder: u128,
pub duration: core::time::Duration,
_phantom: PhantomData<T>,
}
impl<T> Lease<T> {
pub fn new(holder: u128, duration: core::time::Duration) -> Result<Self, LeaseError> {
if duration.is_zero() {
return Err(LeaseError::InvalidDuration);
}
Ok(Self {
holder,
duration,
_phantom: PhantomData,
})
}
#[inline]
pub fn duration(&self) -> core::time::Duration {
self.duration
}
#[inline]
pub fn holder(&self) -> u128 {
self.holder
}
}
pub trait DistributedBorrow<T> {
fn try_hire(
&self,
candidate_id: u128,
term: core::time::Duration,
) -> Result<Lease<T>, LeaseError>;
}
impl<T> DistributedBorrow<T> for Sovereign<T> {
fn try_hire(
&self,
candidate_id: u128,
term: core::time::Duration,
) -> Result<Lease<T>, LeaseError> {
let current = self.state.load(Ordering::SeqCst);
if current == SovereignState::Exiled as u8 {
return Err(LeaseError::AlreadyLeased);
}
self.state
.store(SovereignState::Exiled as u8, Ordering::SeqCst);
Lease::<T>::new(candidate_id, term)
}
}
pub trait VerifiedAnnex<T> {
fn annex_verified(&self) -> Result<ProofCarrying<()>, AnnexError>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_sovereign_new() {
let s = Sovereign::new(42i32);
assert_eq!(s.state(), SovereignState::Domestic);
assert!(s.is_domestic());
assert!(!s.is_exiled());
}
#[test]
fn test_sovereign_new_exiled() {
let s = Sovereign::new_exiled(42i32);
assert_eq!(s.state(), SovereignState::Exiled);
assert!(s.is_exiled());
assert!(!s.is_domestic());
}
#[test]
fn test_sovereign_deref() {
let s = Sovereign::new(42i32);
assert_eq!(*s, 42);
}
#[test]
fn test_sovereign_deref_mut() {
let mut s = Sovereign::new(42i32);
*s = 100;
assert_eq!(*s, 100);
}
#[test]
fn test_sovereign_annex() {
let s = Sovereign::new(42i32);
assert!(s.annex().is_ok());
assert_eq!(s.state(), SovereignState::Exiled);
assert!(s.is_exiled());
}
#[test]
fn test_sovereign_double_annex() {
let s = Sovereign::new(42i32);
assert!(s.annex().is_ok());
assert!(s.annex().is_err());
}
#[test]
fn test_sovereign_repatriate() {
let s = Sovereign::new(42i32);
s.annex().unwrap();
assert!(s.is_exiled());
let token = unsafe { RepatriationToken::new() };
s.repatriate(token);
assert!(s.is_domestic());
assert_eq!(*s, 42);
}
#[test]
#[should_panic(expected = "SOVEREIGNTY VIOLATION")]
fn test_sovereignty_violation() {
let s = Sovereign::new(42i32);
s.annex().unwrap();
let _ = *s; }
#[test]
fn test_try_get_domestic() {
let s = Sovereign::new(42i32);
assert_eq!(*s.try_get().unwrap(), 42);
}
#[test]
fn test_try_get_exiled() {
let s = Sovereign::new(42i32);
s.annex().unwrap();
assert!(matches!(
s.try_get(),
Err(SovereigntyError::ForeignJurisdiction)
));
}
#[test]
fn test_proof_carrying() {
let proof = ProofCarrying::new_unchecked(42i32);
assert_eq!(proof.value, 42);
assert_eq!(proof.into_inner(), 42);
}
#[test]
fn test_annex_error_display() {
let e = AnnexError::AlreadyExiled;
assert!(e.to_string().contains("foreign jurisdiction"));
let e = AnnexError::VerificationFailed("test".to_string());
assert!(e.to_string().contains("test"));
}
#[test]
fn test_lease_zero_duration_fails() {
let lease = Lease::<i32>::new(1, core::time::Duration::ZERO);
assert!(matches!(lease, Err(LeaseError::InvalidDuration)));
}
#[test]
fn test_lease_normal_duration() {
let duration = core::time::Duration::from_secs(10);
let lease = Lease::<i32>::new(1, duration).unwrap();
assert_eq!(lease.duration(), duration);
assert_eq!(lease.holder(), 1);
}
#[test]
fn test_map_domestic() {
let s = Sovereign::new(10);
let res = s.map(|x| x * 2);
assert_eq!(res, Ok(20));
}
#[test]
fn test_map_exiled() {
let s = Sovereign::new(10);
s.annex().unwrap();
let res = s.map(|x| x * 2);
assert_eq!(res, Err(SovereigntyError::ForeignJurisdiction));
}
#[test]
fn test_and_then() {
let s = Sovereign::new(10);
let res = s.and_then(|x| {
if *x > 5 {
Ok(*x * 2)
} else {
Err(SovereigntyError::ForeignJurisdiction) }
});
assert_eq!(res, Ok(20));
}
#[test]
fn test_filter() {
let s = Sovereign::new(10);
let res1 = s.filter(|x| *x > 5);
assert_eq!(res1, Ok(Some(&10)));
let res2 = s.filter(|x| *x < 5);
assert_eq!(res2, Ok(None));
s.annex().unwrap();
let res3 = s.filter(|x| *x > 5);
assert_eq!(res3, Err(SovereigntyError::ForeignJurisdiction));
}
#[test]
fn test_modify() {
let mut s = Sovereign::new(10);
s.modify(|x| *x += 1).unwrap();
assert_eq!(*s, 11);
s.annex().unwrap();
let res = s.modify(|x| *x += 1);
assert_eq!(res, Err(SovereigntyError::ForeignJurisdiction));
}
}