pub mod backoff;
pub use backoff::ExponentialBackoff;
use std::sync::Arc;
use moonproof_utils::StateCell;
use tokio::sync::watch;
use crate::error::{Result, WalletError};
use crate::facade::state::FacadeState;
#[derive(Debug, Clone)]
pub struct WalletRuntime {
inner: Arc<Inner>,
}
#[derive(Debug)]
struct Inner {
state: StateCell<FacadeState>,
cancel: CancellationToken,
}
impl WalletRuntime {
pub fn new(initial: FacadeState) -> Self {
Self {
inner: Arc::new(Inner {
state: StateCell::new(initial),
cancel: CancellationToken::new(),
}),
}
}
pub async fn current(&self) -> FacadeState {
self.inner.state.current().await
}
pub async fn protocol_version(&self) -> crate::abstractions::ProtocolVersion {
self.inner.state.current().await.protocol_version()
}
pub fn changes(&self) -> watch::Receiver<FacadeState> {
self.inner.state.changes()
}
pub async fn apply<F>(&self, f: F) -> Result<()>
where
F: FnOnce(FacadeState) -> Result<FacadeState>,
{
self.inner.state.apply::<_, WalletError>(f).await
}
pub async fn set(&self, state: FacadeState) {
self.inner.state.set(state).await;
}
pub fn cancel_token(&self) -> CancellationToken {
self.inner.cancel.clone()
}
pub fn shutdown(&self) {
self.inner.cancel.cancel();
}
}
#[derive(Debug, Clone)]
pub struct CancellationToken {
inner: Arc<TokenInner>,
}
#[derive(Debug)]
struct TokenInner {
cancelled: std::sync::atomic::AtomicBool,
notify: tokio::sync::Notify,
}
impl CancellationToken {
pub fn new() -> Self {
Self {
inner: Arc::new(TokenInner {
cancelled: std::sync::atomic::AtomicBool::new(false),
notify: tokio::sync::Notify::new(),
}),
}
}
pub fn cancel(&self) {
if !self
.inner
.cancelled
.swap(true, std::sync::atomic::Ordering::SeqCst)
{
self.inner.notify.notify_waiters();
}
}
pub fn is_cancelled(&self) -> bool {
self.inner
.cancelled
.load(std::sync::atomic::Ordering::SeqCst)
}
pub async fn cancelled(&self) {
if self.is_cancelled() {
return;
}
let notified = self.inner.notify.notified();
if self.is_cancelled() {
return;
}
notified.await;
}
pub async fn run_until_cancelled<F, T>(&self, fut: F) -> Option<T>
where
F: std::future::Future<Output = T>,
{
tokio::select! {
res = fut => Some(res),
() = self.cancelled() => None,
}
}
}
impl Default for CancellationToken {
fn default() -> Self {
Self::new()
}
}
pub use std::time::Duration as StdDuration;
#[cfg(test)]
mod tests {
use super::*;
use crate::abstractions::NetworkId;
use crate::dust::DustState;
use crate::shielded::ShieldedState;
use crate::unshielded::UnshieldedState;
use moonproof_ledger::base_crypto::time::Duration as BcDuration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use moonproof_ledger::zswap::keys::{SecretKeys as ZswapSecretKeys, Seed as ZswapSeed};
fn empty_facade() -> FacadeState {
let sh = ShieldedState::init_empty(
&ZswapSecretKeys::from(ZswapSeed::from([0x01u8; 32])),
NetworkId::Undeployed,
);
let du = DustState::init_empty(
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: BcDuration::from_secs(60),
},
&DustSecretKey::derive_secret_key(&[0x02u8; 32]),
NetworkId::Undeployed,
);
FacadeState::new(sh, UnshieldedState::empty(), du, NetworkId::Undeployed)
}
#[tokio::test(flavor = "current_thread")]
async fn apply_broadcasts_to_subscribers() {
let runtime = WalletRuntime::new(empty_facade());
let mut rx = runtime.changes();
let _ = rx.borrow_and_update().clone();
runtime.apply(Ok).await.unwrap();
rx.changed().await.unwrap();
}
#[tokio::test(flavor = "current_thread")]
async fn apply_preserves_state_on_error() {
let runtime = WalletRuntime::new(empty_facade());
let before = runtime.current().await;
let result: Result<()> = runtime
.apply(|_| Err(crate::error::WalletError::Serialization("boom".to_owned())))
.await;
assert!(result.is_err());
let after = runtime.current().await;
assert_eq!(before.network_id().as_str(), after.network_id().as_str(),);
}
#[tokio::test(flavor = "current_thread")]
async fn cancel_token_signals_waiters() {
let runtime = WalletRuntime::new(empty_facade());
let token = runtime.cancel_token();
let task = {
let token = token.clone();
tokio::spawn(async move {
token.cancelled().await;
42
})
};
runtime.shutdown();
let result = task.await.unwrap();
assert_eq!(result, 42);
assert!(token.is_cancelled());
}
#[tokio::test(flavor = "current_thread")]
async fn run_until_cancelled_yields_none_on_cancel() {
let runtime = WalletRuntime::new(empty_facade());
let token = runtime.cancel_token();
runtime.shutdown();
let result: Option<i32> = token
.run_until_cancelled(async {
tokio::time::sleep(std::time::Duration::from_secs(60)).await;
7
})
.await;
assert_eq!(result, None);
}
#[tokio::test(flavor = "current_thread")]
async fn shared_runtime_clones_share_state() {
let runtime = WalletRuntime::new(empty_facade());
let copy = runtime.clone();
let token_a = runtime.cancel_token();
let token_b = copy.cancel_token();
copy.shutdown();
assert!(token_a.is_cancelled());
assert!(token_b.is_cancelled());
}
}