use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::{
DustGenerationInfo, DustOutput, DustParameters, DustPublicKey, QualifiedDustOutput,
};
use crate::dust::state::DustState;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustGenerationDetails {
pub dtime: Option<Timestamp>,
pub max_cap: u128,
pub max_cap_reached_at: Timestamp,
pub generated_now: u128,
pub rate: u128,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustFullInfo {
pub token: QualifiedDustOutput,
pub details: DustGenerationDetails,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UtxoWithDustEstimate<U> {
pub utxo: U,
pub dust: DustGenerationDetails,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct NightUtxoForDust {
pub value: u128,
pub ctime: Timestamp,
pub registered_for_dust_generation: bool,
}
impl NightUtxoForDust {
#[inline]
#[must_use]
pub const fn new(value: u128, ctime: Timestamp, registered_for_dust_generation: bool) -> Self {
Self {
value,
ctime,
registered_for_dust_generation,
}
}
}
#[must_use]
pub fn wallet_balance(state: &DustState, time: Timestamp) -> u128 {
state.local().wallet_balance(time)
}
#[must_use]
pub fn available_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
let now = resolve_time(state, time);
available_dust_coins(state)
.filter_map(|coin| build_full_info(state, coin, now))
.collect()
}
#[must_use]
pub fn pending_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
let now = resolve_time(state, time);
state
.pending()
.filter_map(|p| build_full_info(state, p.utxo, now))
.collect()
}
#[must_use]
pub fn total_coins(state: &DustState, time: Option<Timestamp>) -> Vec<DustFullInfo> {
let now = resolve_time(state, time);
let mut out = available_coins(state, Some(now));
out.extend(pending_coins(state, Some(now)));
out
}
#[must_use]
pub fn available_coins_with_generated_dust(
state: &DustState,
time: Timestamp,
) -> Vec<(QualifiedDustOutput, u128)> {
available_coins(state, Some(time))
.into_iter()
.map(|info| (info.token, info.details.generated_now))
.collect()
}
#[must_use]
pub fn generation_info(
state: &DustState,
coin: &QualifiedDustOutput,
) -> Option<DustGenerationInfo> {
state.local().generation_info(coin)
}
#[must_use]
pub fn estimate_dust_generation(
state: &DustState,
night_utxos: &[NightUtxoForDust],
current_time: Timestamp,
) -> Vec<UtxoWithDustEstimate<NightUtxoForDust>> {
let dust_pk = state.public_key();
let params = state.parameters();
night_utxos
.iter()
.map(|utxo| {
let gen_info = fake_generation_info(*utxo, dust_pk);
let fake_dust = fake_dust_token(dust_pk, *utxo);
let details = build_details(¶ms, &gen_info, &fake_dust, current_time);
UtxoWithDustEstimate {
utxo: *utxo,
dust: details,
}
})
.collect()
}
#[must_use]
pub fn split_night_utxos<U: Clone>(
utxos: &[UtxoWithDustEstimate<U>],
) -> (Vec<UtxoWithDustEstimate<U>>, Vec<UtxoWithDustEstimate<U>>) {
let mut sorted: Vec<UtxoWithDustEstimate<U>> = utxos.to_vec();
sorted.sort_by_key(|u| std::cmp::Reverse(u.dust.generated_now));
if sorted.is_empty() {
return (Vec::new(), Vec::new());
}
let fallible = sorted.split_off(1);
(sorted, fallible)
}
fn build_full_info(
state: &DustState,
coin: QualifiedDustOutput,
now: Timestamp,
) -> Option<DustFullInfo> {
let gen_info = state.local().generation_info(&coin)?;
let details = build_details(&state.local().params, &gen_info, &coin, now);
Some(DustFullInfo {
token: coin,
details,
})
}
fn available_dust_coins(state: &DustState) -> impl Iterator<Item = QualifiedDustOutput> + '_ {
let pending_nonces: indexmap::IndexSet<_> = state.pending().map(|p| p.utxo.nonce).collect();
state
.local()
.utxos()
.filter(move |coin| !pending_nonces.contains(&coin.nonce))
}
fn build_details<C: Into<DustOutput> + Copy>(
params: &DustParameters,
gen_info: &DustGenerationInfo,
coin: &C,
now: Timestamp,
) -> DustGenerationDetails {
let coin_output: DustOutput = (*coin).into();
let generated = coin_output.updated_value(gen_info, now, params);
let rate = gen_info
.value
.saturating_mul(u128::from(params.generation_decay_rate));
let max_cap = gen_info
.value
.saturating_mul(u128::from(params.night_dust_ratio));
let max_cap_reached_at = coin_output.ctime + params.time_to_cap();
DustGenerationDetails {
dtime: option_dtime(gen_info),
max_cap,
max_cap_reached_at,
generated_now: generated,
rate,
}
}
#[inline]
fn option_dtime(gen_info: &DustGenerationInfo) -> Option<Timestamp> {
if gen_info.dtime == Timestamp::default() || gen_info.dtime == Timestamp::MAX {
None
} else {
Some(gen_info.dtime)
}
}
#[inline]
fn resolve_time(state: &DustState, time: Option<Timestamp>) -> Timestamp {
time.unwrap_or_else(|| state.sync_time())
}
fn fake_generation_info(utxo: NightUtxoForDust, dust_pk: DustPublicKey) -> DustGenerationInfo {
DustGenerationInfo {
value: utxo.value,
owner: dust_pk,
nonce: moonproof_ledger::ledger::dust::InitialNonce(
moonproof_ledger::base_crypto::hash::HashOutput([0; 32]),
),
dtime: Timestamp::MAX,
}
}
fn fake_dust_token(dust_pk: DustPublicKey, utxo: NightUtxoForDust) -> DustOutput {
use moonproof_ledger::transient_crypto::curve::Fr;
DustOutput {
initial_value: 0,
owner: dust_pk,
nonce: Fr::default(),
seq: 0,
ctime: utxo.ctime,
}
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use crate::abstractions::NetworkId;
use crate::dust::state::DustState;
fn params() -> DustParameters {
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: Duration::from_secs(60),
}
}
fn empty_state() -> DustState {
let sk = DustSecretKey::derive_secret_key(&[0x42u8; 32]);
DustState::init_empty(params(), &sk, NetworkId::Undeployed)
}
#[test]
fn empty_state_has_zero_balance_and_no_coins() {
let s = empty_state();
assert_eq!(wallet_balance(&s, Timestamp::from_secs(100)), 0);
assert_eq!(available_coins(&s, None), [] as [DustFullInfo; 0]);
assert_eq!(pending_coins(&s, None), [] as [DustFullInfo; 0]);
assert_eq!(total_coins(&s, None), [] as [DustFullInfo; 0]);
}
#[test]
fn estimate_dust_generation_yields_one_entry_per_input() {
let s = empty_state();
let utxos = vec![
NightUtxoForDust::new(50_000, Timestamp::from_secs(0), false),
NightUtxoForDust::new(150_000, Timestamp::from_secs(0), false),
];
let estimates = estimate_dust_generation(&s, &utxos, Timestamp::from_secs(60));
assert_eq!(estimates.len(), 2);
assert!(estimates[1].dust.rate > estimates[0].dust.rate);
assert!(estimates[1].dust.max_cap > estimates[0].dust.max_cap);
}
#[test]
fn estimate_dust_generation_respects_time_to_cap() {
let s = empty_state();
let utxos = vec![NightUtxoForDust::new(1_000, Timestamp::from_secs(0), false)];
let est = estimate_dust_generation(&s, &utxos, Timestamp::from_secs(1_000));
let expected_cap = 1_000u128 * 1_000u128;
assert_eq!(est[0].dust.max_cap, expected_cap);
assert_eq!(est[0].dust.generated_now, expected_cap);
}
#[test]
fn split_night_utxos_puts_highest_in_guaranteed() {
let utxos: Vec<UtxoWithDustEstimate<NightUtxoForDust>> = vec![
UtxoWithDustEstimate {
utxo: NightUtxoForDust::new(100, Timestamp::from_secs(0), false),
dust: DustGenerationDetails {
dtime: None,
max_cap: 1_000,
max_cap_reached_at: Timestamp::from_secs(1_000),
generated_now: 100,
rate: 1,
},
},
UtxoWithDustEstimate {
utxo: NightUtxoForDust::new(500, Timestamp::from_secs(0), false),
dust: DustGenerationDetails {
dtime: None,
max_cap: 5_000,
max_cap_reached_at: Timestamp::from_secs(5_000),
generated_now: 500,
rate: 5,
},
},
UtxoWithDustEstimate {
utxo: NightUtxoForDust::new(200, Timestamp::from_secs(0), false),
dust: DustGenerationDetails {
dtime: None,
max_cap: 2_000,
max_cap_reached_at: Timestamp::from_secs(2_000),
generated_now: 200,
rate: 2,
},
},
];
let (guaranteed, fallible) = split_night_utxos(&utxos);
assert_eq!(guaranteed.len(), 1);
assert_eq!(fallible.len(), 2);
assert_eq!(guaranteed[0].utxo.value, 500); assert_eq!(fallible[0].utxo.value, 200);
assert_eq!(fallible[1].utxo.value, 100);
}
#[test]
fn split_night_utxos_handles_empty_input() {
let utxos: Vec<UtxoWithDustEstimate<NightUtxoForDust>> = Vec::new();
let (guaranteed, fallible) = split_night_utxos(&utxos);
assert_eq!(
guaranteed,
[] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]
);
assert_eq!(fallible, [] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]);
}
#[test]
fn split_night_utxos_with_single_input_returns_only_guaranteed() {
let one = UtxoWithDustEstimate {
utxo: NightUtxoForDust::new(123, Timestamp::from_secs(0), false),
dust: DustGenerationDetails {
dtime: None,
max_cap: 1_230,
max_cap_reached_at: Timestamp::from_secs(1_230),
generated_now: 7,
rate: 1,
},
};
let (guaranteed, fallible) = split_night_utxos(std::slice::from_ref(&one));
assert_eq!(guaranteed.len(), 1);
assert_eq!(fallible, [] as [UtxoWithDustEstimate<NightUtxoForDust>; 0]);
assert_eq!(guaranteed[0].utxo.value, 123);
}
#[test]
fn resolve_time_falls_back_to_sync_time_when_none() {
let s = empty_state();
assert_eq!(resolve_time(&s, None), Timestamp::default());
let explicit = Timestamp::from_secs(99);
assert_eq!(resolve_time(&s, Some(explicit)), explicit);
}
}