use std::collections::BTreeSet;
use indexmap::IndexSet;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::QualifiedDustOutput;
use crate::dust::balances::{
available_coins_with_generated_dust, estimate_dust_generation, split_night_utxos,
NightUtxoForDust, UtxoWithDustEstimate,
};
use crate::dust::state::{CoinWithFee, DustState};
use crate::error::{Result, WalletError};
use crate::unshielded::UtxoWithMeta;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DustRegistrationSpec {
pub dust_address: Option<moonproof_ledger::ledger::dust::DustPublicKey>,
pub allow_fee_payment: u128,
}
#[derive(Debug, Clone)]
pub struct DustGenerationRecipe {
pub guaranteed_inputs: Vec<UtxoWithMeta>,
pub fallible_inputs: Vec<UtxoWithMeta>,
pub guaranteed_change_value: u128,
pub fallible_change_value: u128,
pub registration: DustRegistrationSpec,
pub ctime: Timestamp,
}
impl DustGenerationRecipe {
#[must_use]
pub fn has_guaranteed(&self) -> bool {
!self.guaranteed_inputs.is_empty()
}
#[must_use]
pub fn has_fallible(&self) -> bool {
!self.fallible_inputs.is_empty()
}
#[must_use]
pub fn total_inputs(&self) -> usize {
self.guaranteed_inputs.len() + self.fallible_inputs.len()
}
}
pub fn build_dust_generation_recipe(
state: &DustState,
night_utxos: &[UtxoWithMeta],
dust_receiver: Option<moonproof_ledger::ledger::dust::DustPublicKey>,
current_time: Timestamp,
) -> Result<DustGenerationRecipe> {
if night_utxos.is_empty() {
return Ok(DustGenerationRecipe {
guaranteed_inputs: Vec::new(),
fallible_inputs: Vec::new(),
guaranteed_change_value: 0,
fallible_change_value: 0,
registration: DustRegistrationSpec {
dust_address: dust_receiver,
allow_fee_payment: 0,
},
ctime: current_time,
});
}
let projections: Vec<NightUtxoForDust> = night_utxos.iter().map(utxo_to_dust_view).collect();
let estimates: Vec<UtxoWithDustEstimate<usize>> =
estimate_dust_generation(state, &projections, current_time)
.into_iter()
.enumerate()
.map(|(i, e)| UtxoWithDustEstimate {
utxo: i,
dust: e.dust,
})
.collect();
let (guaranteed_estimates, fallible_estimates) = split_night_utxos(&estimates);
let guaranteed_inputs: Vec<UtxoWithMeta> = guaranteed_estimates
.iter()
.map(|e| night_utxos[e.utxo].clone())
.collect();
let fallible_inputs: Vec<UtxoWithMeta> = fallible_estimates
.iter()
.map(|e| night_utxos[e.utxo].clone())
.collect();
let guaranteed_change_value: u128 = guaranteed_inputs.iter().map(|u| u.utxo.value).sum();
let fallible_change_value: u128 = fallible_inputs.iter().map(|u| u.utxo.value).sum();
let allow_fee_payment = if dust_receiver.is_some() {
sum_unregistered_generated_dust(&guaranteed_estimates, night_utxos)
} else {
0
};
Ok(DustGenerationRecipe {
guaranteed_inputs,
fallible_inputs,
guaranteed_change_value,
fallible_change_value,
registration: DustRegistrationSpec {
dust_address: dust_receiver,
allow_fee_payment,
},
ctime: current_time,
})
}
fn utxo_to_dust_view(utxo: &UtxoWithMeta) -> NightUtxoForDust {
let ctime = u64::try_from(utxo.meta.ctime).unwrap_or(0);
NightUtxoForDust::new(
utxo.utxo.value,
Timestamp::from_secs(ctime),
utxo.meta.registered_for_dust_generation,
)
}
fn sum_unregistered_generated_dust(
estimates: &[UtxoWithDustEstimate<usize>],
night_utxos: &[UtxoWithMeta],
) -> u128 {
estimates
.iter()
.filter(|e| !night_utxos[e.utxo].meta.registered_for_dust_generation)
.map(|e| e.dust.generated_now)
.sum()
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FeeCoverageEstimate {
Reachable { seconds: u64, at: Timestamp },
NoGeneration,
ExceedsCap,
}
#[must_use]
pub fn fee_coverage_estimate(
state: &DustState,
night_utxos: &[UtxoWithMeta],
fee: u128,
now: Timestamp,
) -> FeeCoverageEstimate {
let views: Vec<NightUtxoForDust> = night_utxos.iter().map(utxo_to_dust_view).collect();
let claimable: Vec<_> = estimate_dust_generation(state, &views, now)
.into_iter()
.filter(|e| !e.utxo.registered_for_dust_generation)
.collect();
if fee == 0 || claimable.iter().any(|e| e.dust.generated_now >= fee) {
return FeeCoverageEstimate::Reachable {
seconds: 0,
at: now,
};
}
let generating: Vec<_> = claimable.iter().filter(|e| e.dust.rate > 0).collect();
if generating.is_empty() {
return FeeCoverageEstimate::NoGeneration;
}
let seconds = generating
.iter()
.filter(|e| e.dust.max_cap >= fee)
.map(|e| {
let until_created = e.utxo.ctime.to_secs().saturating_sub(now.to_secs());
let to_generate = (fee - e.dust.generated_now).div_ceil(e.dust.rate);
u128::from(until_created).saturating_add(to_generate)
})
.min();
match seconds {
Some(s) => {
let seconds = u64::try_from(s).unwrap_or(u64::MAX);
FeeCoverageEstimate::Reachable {
seconds,
at: Timestamp::from_secs(now.to_secs().saturating_add(seconds)),
}
}
None => FeeCoverageEstimate::ExceedsCap,
}
}
#[derive(Debug, Clone)]
pub struct DustBalancingRecipe {
pub inputs: Vec<CoinWithFee>,
pub total_fee: u128,
}
pub fn compute_fee_balancing_recipe(
state: &DustState,
initial_fee: u128,
current_time: Timestamp,
mut fee_estimator: impl FnMut(&[CoinWithFee]) -> Result<u128>,
) -> Result<DustBalancingRecipe> {
let available = available_coins_with_generated_dust(state, current_time);
if available.is_empty() && initial_fee > 0 {
return Err(WalletError::InsufficientFunds {
token: "dust".to_owned(),
});
}
let mut current_fee = initial_fee;
for _ in 0..=(available.len() + 1) {
let picked = pick_dust_coins(&available, current_fee)?;
let new_fee = fee_estimator(&picked)?;
let coverage: u128 = picked.iter().map(|c| c.fee).sum();
if new_fee <= coverage {
let converged_inputs = distribute_fee_across_inputs(picked, new_fee);
return Ok(DustBalancingRecipe {
inputs: converged_inputs,
total_fee: new_fee,
});
}
current_fee = new_fee;
}
Err(WalletError::Dust(format!(
"fee balancing did not converge after {} iterations (current fee {})",
available.len() + 2,
current_fee
)))
}
fn pick_dust_coins(
available: &[(QualifiedDustOutput, u128)],
target: u128,
) -> Result<Vec<CoinWithFee>> {
if target == 0 {
return Ok(Vec::new());
}
let mut non_zero: Vec<(QualifiedDustOutput, u128)> = available
.iter()
.filter(|(_, value)| *value > 0)
.copied()
.collect();
if let Some((utxo, generated_value)) = non_zero
.iter()
.copied()
.filter(|(_, value)| *value >= target)
.min_by_key(|(_, value)| *value)
{
return Ok(vec![CoinWithFee::new(utxo, generated_value)]);
}
non_zero.sort_by_key(|a| std::cmp::Reverse(a.1));
let mut covered: u128 = 0;
let mut picked = Vec::new();
for (utxo, generated_value) in &non_zero {
if covered >= target {
break;
}
picked.push(CoinWithFee::new(*utxo, *generated_value));
covered = covered.saturating_add(*generated_value);
}
if covered < target {
return Err(WalletError::InsufficientFunds {
token: "dust".to_owned(),
});
}
Ok(picked)
}
fn distribute_fee_across_inputs(inputs: Vec<CoinWithFee>, fee: u128) -> Vec<CoinWithFee> {
let mut remaining = fee;
let mut out = Vec::with_capacity(inputs.len());
for c in inputs {
let deduction = remaining.min(c.fee);
out.push(CoinWithFee::new(c.utxo, deduction));
remaining = remaining.saturating_sub(deduction);
}
out
}
#[must_use]
pub fn find_available_segment_id(used: &BTreeSet<u16>) -> Option<u16> {
(1u16..=u16::MAX).find(|s| !used.contains(s))
}
#[must_use]
pub fn next_segment_id_after(used_segments: impl IntoIterator<Item = u16>) -> Option<u16> {
let used: IndexSet<u16> = used_segments.into_iter().collect();
(1u16..=u16::MAX).find(|s| !used.contains(s))
}
#[cfg(test)]
mod tests {
use super::*;
mod fee_coverage {
use super::*;
use crate::abstractions::NetworkId;
use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta};
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
fn state(night_dust_ratio: u64, generation_decay_rate: u32) -> DustState {
DustState::init_empty(
DustParameters {
night_dust_ratio,
generation_decay_rate,
dust_grace_period: Duration::from_secs(60),
},
&DustSecretKey::derive_secret_key(&[0x02u8; 32]),
NetworkId::Undeployed,
)
}
fn utxo(value: u128, ctime: i64, registered: bool) -> UtxoWithMeta {
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new([1; 32], 0),
value,
crate::TokenType::new("native"),
[0; 32],
),
UtxoMeta::new(ctime, registered),
)
}
#[test]
fn seconds_until_one_utxo_covers_the_fee() {
let est = fee_coverage_estimate(
&state(1_000, 3),
&[utxo(10, 0, false)],
100,
Timestamp::from_secs(0),
);
assert_eq!(
est,
FeeCoverageEstimate::Reachable {
seconds: 4,
at: Timestamp::from_secs(4)
}
);
}
#[test]
fn already_covered_is_zero_seconds() {
let est = fee_coverage_estimate(
&state(1_000, 3),
&[utxo(10, 0, false)],
100,
Timestamp::from_secs(10),
);
assert!(matches!(
est,
FeeCoverageEstimate::Reachable { seconds: 0, .. }
));
}
#[test]
fn a_cap_below_the_fee_is_unreachable() {
let est = fee_coverage_estimate(
&state(5, 3),
&[utxo(10, 0, false)],
100,
Timestamp::from_secs(0),
);
assert_eq!(est, FeeCoverageEstimate::ExceedsCap);
}
#[test]
fn registered_utxos_do_not_count() {
let est = fee_coverage_estimate(
&state(1_000, 3),
&[utxo(10, 0, true)],
100,
Timestamp::from_secs(0),
);
assert_eq!(est, FeeCoverageEstimate::NoGeneration);
}
}
use moonproof_ledger::base_crypto::time::{Duration, Timestamp};
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use crate::abstractions::NetworkId;
fn params() -> DustParameters {
DustParameters {
night_dust_ratio: 1_000,
generation_decay_rate: 1,
dust_grace_period: Duration::from_secs(60),
}
}
fn state() -> DustState {
let sk = DustSecretKey::derive_secret_key(&[0x42u8; 32]);
DustState::init_empty(params(), &sk, NetworkId::Undeployed)
}
fn night_utxo(value: u128, ctime_secs: i64, registered: bool) -> UtxoWithMeta {
use crate::types::TokenType;
use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta};
let mut intent_hash = [0u8; 32];
intent_hash[0] = (value & 0xff) as u8;
intent_hash[1] = ((value >> 8) & 0xff) as u8;
intent_hash[2] = ctime_secs.to_le_bytes()[0];
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new(intent_hash, 0),
value,
TokenType::new("native"),
[0u8; 32],
),
UtxoMeta::new(ctime_secs, registered),
)
}
#[test]
fn build_recipe_for_zero_utxos_yields_address_only_registration() {
let s = state();
let pk = s.public_key();
let r = build_dust_generation_recipe(&s, &[], Some(pk), Timestamp::from_secs(10)).unwrap();
assert_eq!(r.total_inputs(), 0);
assert_eq!(r.registration.dust_address, Some(pk));
assert_eq!(r.registration.allow_fee_payment, 0);
assert_eq!(r.ctime, Timestamp::from_secs(10));
}
#[test]
fn build_recipe_for_zero_utxos_deregister_clears_address() {
let s = state();
let r = build_dust_generation_recipe(&s, &[], None, Timestamp::from_secs(10)).unwrap();
assert!(r.registration.dust_address.is_none());
assert_eq!(r.registration.allow_fee_payment, 0);
}
#[test]
fn build_recipe_puts_one_utxo_in_guaranteed() {
let s = state();
let utxos = vec![night_utxo(150_000, 0, false)];
let r = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
assert_eq!(r.guaranteed_inputs.len(), 1);
assert_eq!(r.fallible_inputs, [] as [UtxoWithMeta; 0]);
assert_eq!(r.guaranteed_inputs[0].utxo.value, 150_000);
assert_eq!(r.guaranteed_change_value, 150_000);
assert_eq!(r.fallible_change_value, 0);
}
#[test]
fn build_recipe_with_multiple_utxos_splits_one_to_guaranteed() {
let s = state();
let utxos = vec![
night_utxo(100_000, 0, false),
night_utxo(500_000, 0, false),
night_utxo(200_000, 0, false),
];
let r = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
assert_eq!(r.guaranteed_inputs.len(), 1);
assert_eq!(r.guaranteed_inputs[0].utxo.value, 500_000);
assert_eq!(r.fallible_inputs.len(), 2);
assert_eq!(r.fallible_change_value, 300_000);
assert_eq!(r.guaranteed_change_value, 500_000);
}
#[test]
fn build_recipe_register_sums_unregistered_for_fee_payment() {
let s = state();
let utxos = vec![night_utxo(100_000, 0, true), night_utxo(500_000, 0, false)];
let r = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
assert!(r.registration.allow_fee_payment > 0);
}
#[test]
fn build_recipe_deregister_never_authorizes_fee_payment() {
let s = state();
let utxos = vec![night_utxo(500_000, 0, false)];
let r = build_dust_generation_recipe(&s, &utxos, None, Timestamp::from_secs(10)).unwrap();
assert_eq!(r.registration.allow_fee_payment, 0);
assert!(r.registration.dust_address.is_none());
}
#[test]
fn balancing_with_zero_initial_fee_picks_no_inputs() {
let s = state();
let r = compute_fee_balancing_recipe(
&s,
0,
Timestamp::from_secs(10),
|_| Ok(0),
)
.unwrap();
assert_eq!(r.inputs, [] as [CoinWithFee; 0]);
assert_eq!(r.total_fee, 0);
}
#[test]
fn balancing_with_no_dust_and_nonzero_fee_errors_insufficient() {
let s = state();
let err = compute_fee_balancing_recipe(&s, 100, Timestamp::from_secs(10), |_| Ok(100))
.unwrap_err();
assert!(matches!(err, WalletError::InsufficientFunds { .. }));
}
#[test]
fn find_available_segment_skips_used_starting_at_one() {
let mut used = BTreeSet::new();
used.insert(1);
used.insert(2);
used.insert(4);
assert_eq!(find_available_segment_id(&used), Some(3));
}
#[test]
fn find_available_segment_returns_one_when_empty() {
let used = BTreeSet::new();
assert_eq!(find_available_segment_id(&used), Some(1));
}
#[test]
fn next_segment_id_after_iter_finds_first_gap() {
assert_eq!(next_segment_id_after([1u16, 2, 3, 5]), Some(4));
assert_eq!(next_segment_id_after([2u16, 3, 4]), Some(1));
assert_eq!(next_segment_id_after(std::iter::empty::<u16>()), Some(1));
}
#[test]
fn distribute_fee_drains_first_input_fully_then_partial() {
let inputs = vec![
CoinWithFee::new(dummy_utxo(), 100),
CoinWithFee::new(dummy_utxo(), 100),
CoinWithFee::new(dummy_utxo(), 100),
];
let dist = distribute_fee_across_inputs(inputs, 250);
assert_eq!(dist[0].fee, 100);
assert_eq!(dist[1].fee, 100);
assert_eq!(dist[2].fee, 50);
let total: u128 = dist.iter().map(|c| c.fee).sum();
assert_eq!(total, 250);
}
#[test]
fn distribute_fee_zero_yields_zero_per_input() {
let inputs = vec![
CoinWithFee::new(dummy_utxo(), 100),
CoinWithFee::new(dummy_utxo(), 50),
];
let dist = distribute_fee_across_inputs(inputs, 0);
assert!(dist.iter().all(|c| c.fee == 0));
}
#[test]
fn distribute_fee_does_not_overdraw_total_capacity() {
let inputs = vec![
CoinWithFee::new(dummy_utxo(), 50),
CoinWithFee::new(dummy_utxo(), 50),
];
let dist = distribute_fee_across_inputs(inputs, 200);
let total: u128 = dist.iter().map(|c| c.fee).sum();
assert_eq!(total, 100);
}
#[test]
fn pick_dust_coins_skips_zero_generated_now_coins() {
let available = vec![
(dummy_utxo(), 0), (dummy_utxo(), 100),
(dummy_utxo(), 200),
];
let picked = pick_dust_coins(&available, 150).unwrap();
let total: u128 = picked.iter().map(|c| c.fee).sum();
assert!(total >= 150, "covers target");
assert!(
picked.iter().all(|c| c.fee > 0),
"no zero-value coin in picked set",
);
}
#[test]
fn pick_dust_coins_insufficient_when_only_zero_value_coins() {
let available = vec![(dummy_utxo(), 0), (dummy_utxo(), 0)];
let err = pick_dust_coins(&available, 1).unwrap_err();
assert!(matches!(err, WalletError::InsufficientFunds { .. }));
}
#[test]
fn pick_dust_coins_prefers_single_covering_coin_for_time_to_dismiss() {
let available = vec![
(dummy_utxo(), 50),
(dummy_utxo(), 120),
(dummy_utxo(), 200),
(dummy_utxo(), 500),
];
let picked = pick_dust_coins(&available, 150).unwrap();
assert_eq!(picked.len(), 1);
assert_eq!(picked[0].fee, 200);
let picked_multi = pick_dust_coins(&available, 650).unwrap();
assert_eq!(picked_multi.len(), 2);
assert_eq!(picked_multi[0].fee, 500);
assert_eq!(picked_multi[1].fee, 200);
}
fn dummy_utxo() -> QualifiedDustOutput {
use moonproof_ledger::base_crypto::hash::HashOutput;
use moonproof_ledger::ledger::dust::{DustPublicKey, InitialNonce};
use moonproof_ledger::transient_crypto::curve::Fr;
QualifiedDustOutput {
initial_value: 0,
owner: DustPublicKey(Fr::default()),
nonce: Fr::default(),
seq: 0,
ctime: Timestamp::default(),
backing_night: InitialNonce(HashOutput([0; 32])),
mt_index: 0,
}
}
}