use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
use moonproof_ledger::ledger::dust::{
DustLocalState, DustNullifier, DustParameters, DustPublicKey, DustSecretKey, DustStateChanges,
QualifiedDustOutput,
};
use moonproof_ledger::ledger::events::Event;
use moonproof_ledger::ledger::structure::{BindingKind, ProofKind, SignatureKind, Transaction};
use moonproof_ledger::storage::Storable;
use crate::abstractions::{NetworkId, ProtocolVersion, SyncProgress};
use crate::dust::ledger_adapter::Db;
use crate::error::{Result, WalletError};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct PendingDustSpend {
pub utxo: QualifiedDustOutput,
pub nullifier: DustNullifier,
}
impl PendingDustSpend {
#[inline]
#[must_use]
pub const fn new(utxo: QualifiedDustOutput, nullifier: DustNullifier) -> Self {
Self { utxo, nullifier }
}
}
#[derive(Debug, Clone)]
pub struct DustState {
local: DustLocalState<Db>,
public_key: DustPublicKey,
pending_dust: Vec<PendingDustSpend>,
network_id: NetworkId,
progress: SyncProgress,
protocol_version: ProtocolVersion,
}
impl DustState {
#[must_use]
pub fn init(
local: DustLocalState<Db>,
secret_key: &DustSecretKey,
network_id: NetworkId,
) -> Self {
Self::empty(local, DustPublicKey::from(secret_key.clone()), network_id)
}
#[must_use]
pub fn init_empty(
params: DustParameters,
secret_key: &DustSecretKey,
network_id: NetworkId,
) -> Self {
Self::empty(
DustLocalState::new(params),
DustPublicKey::from(secret_key.clone()),
network_id,
)
}
#[must_use]
pub fn empty(
local: DustLocalState<Db>,
public_key: DustPublicKey,
network_id: NetworkId,
) -> Self {
Self {
local,
public_key,
pending_dust: Vec::new(),
network_id,
progress: SyncProgress::default(),
protocol_version: ProtocolVersion::MIN_SUPPORTED,
}
}
#[must_use]
pub fn restore(
local: DustLocalState<Db>,
public_key: DustPublicKey,
pending_dust: impl IntoIterator<Item = PendingDustSpend>,
progress: SyncProgress,
protocol_version: ProtocolVersion,
network_id: NetworkId,
) -> Self {
Self {
local,
public_key,
pending_dust: pending_dust.into_iter().collect(),
network_id,
progress,
protocol_version,
}
}
#[inline]
#[must_use]
pub fn local(&self) -> &DustLocalState<Db> {
&self.local
}
#[inline]
#[must_use]
pub fn public_key(&self) -> DustPublicKey {
self.public_key
}
#[inline]
#[must_use]
pub fn network_id(&self) -> &NetworkId {
&self.network_id
}
#[inline]
#[must_use]
pub fn progress(&self) -> SyncProgress {
self.progress
}
#[inline]
#[must_use]
pub fn protocol_version(&self) -> ProtocolVersion {
self.protocol_version
}
#[inline]
#[must_use]
pub fn parameters(&self) -> DustParameters {
self.local.params
}
#[inline]
pub fn pending(&self) -> impl ExactSizeIterator<Item = &PendingDustSpend> {
self.pending_dust.iter()
}
#[inline]
#[must_use]
pub fn pending_len(&self) -> usize {
self.pending_dust.len()
}
#[inline]
#[must_use]
pub fn is_pending(&self, nullifier: &DustNullifier) -> bool {
self.pending_dust.iter().any(|p| p.nullifier == *nullifier)
}
#[inline]
#[must_use]
pub fn sync_time(&self) -> Timestamp {
self.local.sync_time
}
#[must_use]
pub fn update_progress(mut self, update: SyncProgressUpdate) -> Self {
if let Some(v) = update.applied_index {
self.progress.applied_index = v;
}
if let Some(v) = update.highest_relevant_wallet_index {
self.progress.highest_relevant_wallet_index = v;
}
if let Some(v) = update.highest_index {
self.progress.highest_index = v;
}
if let Some(v) = update.highest_relevant_index {
self.progress.highest_relevant_index = v;
}
if let Some(v) = update.is_connected {
self.progress.is_connected = v;
}
self
}
#[must_use]
pub fn with_protocol_version(mut self, v: ProtocolVersion) -> Self {
self.protocol_version = v;
self
}
pub fn apply_events_with_changes<'a>(
mut self,
secret_key: &DustSecretKey,
events: impl IntoIterator<Item = &'a Event<Db>>,
current_time: Timestamp,
) -> Result<(Self, Vec<DustStateChanges>)> {
let with_changes = self
.local
.replay_events_with_changes(secret_key, events)
.map_err(|e| WalletError::DustReplay(e.to_string()))?;
let updated = with_changes.result.process_ttls(current_time);
let available_nonces: Vec<_> = updated.utxos().map(|u| u.nonce).collect();
self.local = updated;
self.pending_dust
.retain(|p| available_nonces.iter().any(|n| n == &p.utxo.nonce));
Ok((self, with_changes.changes))
}
pub fn apply_events<'a>(
self,
secret_key: &DustSecretKey,
events: impl IntoIterator<Item = &'a Event<Db>>,
current_time: Timestamp,
) -> Result<Self> {
let (s, _) = self.apply_events_with_changes(secret_key, events, current_time)?;
Ok(s)
}
pub fn spend_coins(
mut self,
secret_key: &DustSecretKey,
coins: &[CoinWithFee],
current_time: Timestamp,
) -> Result<(Vec<UnprovenDustSpend>, Self)> {
let mut spends = Vec::with_capacity(coins.len());
for coin in coins {
let (next, spend) = self
.local
.spend(secret_key, &coin.utxo, coin.fee, current_time)
.map_err(|e| WalletError::DustSpend(e.to_string()))?;
self.pending_dust
.push(PendingDustSpend::new(coin.utxo, spend.old_nullifier));
self.local = next;
spends.push(spend);
}
Ok((spends, self))
}
#[must_use]
pub fn apply_failed<S, P, B>(mut self, tx: &Transaction<S, P, B, Db>) -> Self
where
S: SignatureKind<Db>,
P: ProofKind<Db>,
B: BindingKind<S, P, Db> + Storable<Db>,
{
let standard = match tx {
Transaction::Standard(s) => s,
Transaction::ClaimRewards(_) => return self,
};
let grace = self.local.params.dust_grace_period;
let mut removed: Vec<DustNullifier> = Vec::new();
for intent in standard.intents.values() {
let Some(da) = intent.dust_actions.as_ref() else {
continue;
};
let spend_time: Timestamp = da.ctime;
let advanced_to = advance_past_grace(spend_time, grace);
for spend in da.spends.iter_deref() {
if self
.pending_dust
.iter()
.any(|p| p.nullifier == spend.old_nullifier)
{
self.local = self.local.process_ttls(advanced_to);
removed.push(spend.old_nullifier);
}
}
}
if !removed.is_empty() {
self.pending_dust
.retain(|p| !removed.iter().any(|n| n == &p.nullifier));
}
self
}
#[inline]
#[must_use]
pub fn revert_transaction<S, P, B>(self, tx: &Transaction<S, P, B, Db>) -> Self
where
S: SignatureKind<Db>,
P: ProofKind<Db>,
B: BindingKind<S, P, Db> + Storable<Db>,
{
self.apply_failed(tx)
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct SyncProgressUpdate {
pub applied_index: Option<u64>,
pub highest_relevant_wallet_index: Option<u64>,
pub highest_index: Option<u64>,
pub highest_relevant_index: Option<u64>,
pub is_connected: Option<bool>,
}
impl SyncProgressUpdate {
#[inline]
#[must_use]
pub const fn new() -> Self {
Self {
applied_index: None,
highest_relevant_wallet_index: None,
highest_index: None,
highest_relevant_index: None,
is_connected: None,
}
}
#[inline]
#[must_use]
pub const fn with_applied_index(mut self, v: u64) -> Self {
self.applied_index = Some(v);
self
}
#[inline]
#[must_use]
pub const fn with_highest_relevant_wallet_index(mut self, v: u64) -> Self {
self.highest_relevant_wallet_index = Some(v);
self
}
#[inline]
#[must_use]
pub const fn with_is_connected(mut self, v: bool) -> Self {
self.is_connected = Some(v);
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CoinWithFee {
pub utxo: QualifiedDustOutput,
pub fee: u128,
}
impl CoinWithFee {
#[inline]
#[must_use]
pub const fn new(utxo: QualifiedDustOutput, fee: u128) -> Self {
Self { utxo, fee }
}
}
pub type UnprovenDustSpend = moonproof_ledger::ledger::dust::DustSpend<
moonproof_ledger::ledger::structure::ProofPreimageMarker,
Db,
>;
#[inline]
fn advance_past_grace(ctime: Timestamp, grace: Duration) -> Timestamp {
ctime + grace
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::DustParameters;
fn test_params() -> DustParameters {
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: Duration::from_secs(60),
}
}
fn test_secret_key() -> DustSecretKey {
let seed = [0x42u8; 32];
DustSecretKey::derive_secret_key(&seed)
}
#[test]
fn init_empty_starts_with_zero_pending_and_min_protocol() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
assert_eq!(s.pending_len(), 0);
assert_eq!(s.protocol_version(), ProtocolVersion::MIN_SUPPORTED);
assert_eq!(s.network_id(), &NetworkId::Undeployed);
assert_eq!(s.local().params.night_dust_ratio, 1_000);
assert!(!s.progress().is_connected);
assert_eq!(s.progress().applied_index, 0);
}
#[test]
fn public_key_matches_secret_key_derivation() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
assert_eq!(s.public_key(), DustPublicKey::from(sk.clone()));
}
#[test]
fn update_progress_merges_supplied_fields_only() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed).update_progress(
SyncProgressUpdate::new()
.with_applied_index(42)
.with_is_connected(true),
);
assert_eq!(s.progress().applied_index, 42);
assert!(s.progress().is_connected);
assert_eq!(s.progress().highest_index, 0);
assert_eq!(s.progress().highest_relevant_index, 0);
}
#[test]
fn empty_event_replay_is_a_noop_with_no_changes() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
let (s2, changes) = s
.apply_events_with_changes(&sk, std::iter::empty(), Timestamp::from_secs(100))
.expect("empty replay never errors");
assert!(changes.is_empty());
assert_eq!(s2.pending_len(), 0);
}
#[test]
fn restore_round_trips_pending_entries() {
let sk = test_secret_key();
let pk = DustPublicKey::from(sk.clone());
let local = DustLocalState::new(test_params());
let restored = DustState::restore(
local,
pk,
std::iter::empty(),
SyncProgress {
applied_index: 7,
is_connected: true,
..Default::default()
},
ProtocolVersion(3),
NetworkId::TestNet,
);
assert_eq!(restored.progress().applied_index, 7);
assert!(restored.progress().is_connected);
assert_eq!(restored.protocol_version(), ProtocolVersion(3));
assert_eq!(restored.network_id(), &NetworkId::TestNet);
assert_eq!(restored.pending_len(), 0);
}
#[test]
fn parameters_proxy_reflects_local_state_params() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
assert_eq!(s.parameters().night_dust_ratio, 1_000);
assert_eq!(s.parameters().generation_decay_rate, 1);
assert_eq!(s.parameters().dust_grace_period.as_seconds(), 60);
}
#[test]
fn revert_transaction_on_claim_rewards_is_a_noop() {
let sk = test_secret_key();
let s = DustState::init_empty(test_params(), &sk, NetworkId::Undeployed);
assert_eq!(s.pending_len(), 0);
}
}