use std::collections::BTreeSet;
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::coin_structure::coin::{UserAddress, NIGHT};
use moonproof_ledger::ledger::dust::{DustActions, DustRegistration, DustSpend};
use moonproof_ledger::ledger::error::TransactionProvingError;
use moonproof_ledger::ledger::structure::{
Intent, ProofMarker, ProofPreimageMarker, Transaction, UnshieldedOffer, UtxoOutput, UtxoSpend,
};
use moonproof_ledger::onchain_runtime::cost_model::INITIAL_COST_MODEL;
use moonproof_ledger::serialize::tagged_serialize;
use moonproof_ledger::signatures::{Signature, SigningKey, VerifyingKey};
use moonproof_ledger::storage::arena::Sp;
use moonproof_ledger::storage::db::InMemoryDB;
use moonproof_ledger::storage::storage::HashMap as StorageHashMap;
use moonproof_ledger::storage::Storable;
use moonproof_ledger::transient_crypto::commitment::{PedersenRandomness, PureGeneratorPedersen};
use rand::rngs::OsRng;
use rand::{CryptoRng, RngCore};
use crate::dust::transacting::{DustBalancingRecipe, DustGenerationRecipe};
use crate::error::{Result, WalletError};
use crate::unshielded::ledger_adapter::{to_ledger_intent_hash, NoopProvingProvider};
pub type Db = InMemoryDB;
pub type DustIntent = Intent<Signature, ProofPreimageMarker, PedersenRandomness, Db>;
pub type SignedDustTransaction =
Transaction<Signature, ProofPreimageMarker, PedersenRandomness, Db>;
pub type FinalizedDustTransaction = Transaction<Signature, ProofMarker, PureGeneratorPedersen, Db>;
pub fn build_dust_generation_intent<R: RngCore + CryptoRng>(
recipe: &DustGenerationRecipe,
spender_verifying_key: &VerifyingKey,
ttl: Timestamp,
rng: &mut R,
) -> Result<Option<DustIntent>> {
if recipe.guaranteed_inputs.is_empty()
&& recipe.fallible_inputs.is_empty()
&& recipe.registration.dust_address.is_none()
{
return Ok(None);
}
let guaranteed_offer = build_self_transfer_offer(
&recipe.guaranteed_inputs,
recipe.guaranteed_change_value,
spender_verifying_key,
);
let fallible_offer = build_self_transfer_offer(
&recipe.fallible_inputs,
recipe.fallible_change_value,
spender_verifying_key,
);
let registration: DustRegistration<Signature, Db> = DustRegistration {
night_key: spender_verifying_key.clone(),
dust_address: recipe.registration.dust_address.map(Sp::new),
allow_fee_payment: recipe.registration.allow_fee_payment,
signature: None,
};
let dust_actions: DustActions<Signature, ProofPreimageMarker, Db> = DustActions {
spends: Vec::<DustSpend<ProofPreimageMarker, Db>>::new().into(),
registrations: vec![registration].into(),
ctime: recipe.ctime,
};
let intent: DustIntent = Intent::new(
rng,
guaranteed_offer,
fallible_offer,
Vec::new(), Vec::new(), Vec::new(), Some(dust_actions),
ttl,
);
Ok(Some(intent))
}
pub fn build_dust_balancing_intent<R: RngCore + CryptoRng>(
recipe: &DustBalancingRecipe,
spends: Vec<DustSpend<ProofPreimageMarker, Db>>,
ctime: Timestamp,
ttl: Timestamp,
rng: &mut R,
) -> Result<Option<DustIntent>> {
if spends.is_empty() {
let _ = recipe; return Ok(None);
}
let dust_actions: DustActions<Signature, ProofPreimageMarker, Db> = DustActions {
spends: spends.into(),
registrations: Vec::<DustRegistration<Signature, Db>>::new().into(),
ctime,
};
let intent: DustIntent = Intent::new(
rng,
None, None, Vec::new(),
Vec::new(),
Vec::new(),
Some(dust_actions),
ttl,
);
Ok(Some(intent))
}
pub fn sign_dust_intent<R: RngCore + CryptoRng>(
intent: DustIntent,
segment_id: u16,
night_signing_key: &SigningKey,
rng: &mut R,
) -> Result<DustIntent> {
let guaranteed_count = intent
.guaranteed_unshielded_offer
.as_ref()
.map_or(0, |offer| offer.inputs.len());
let fallible_count = intent
.fallible_unshielded_offer
.as_ref()
.map_or(0, |offer| offer.inputs.len());
let registration_count = intent
.dust_actions
.as_ref()
.map_or(0, |da| da.registrations.len());
let key = night_signing_key.clone();
let guaranteed_keys = vec![key.clone(); guaranteed_count];
let fallible_keys = vec![key.clone(); fallible_count];
let registration_keys = vec![key; registration_count];
sign_dust_intent_multi(
intent,
segment_id,
&guaranteed_keys,
&fallible_keys,
®istration_keys,
rng,
)
}
pub fn sign_dust_intent_multi<R: RngCore + CryptoRng>(
intent: DustIntent,
segment_id: u16,
guaranteed_signing_keys: &[SigningKey],
fallible_signing_keys: &[SigningKey],
dust_registration_signing_keys: &[SigningKey],
rng: &mut R,
) -> Result<DustIntent> {
let guaranteed_count = intent
.guaranteed_unshielded_offer
.as_ref()
.map_or(0, |offer| offer.inputs.len());
let fallible_count = intent
.fallible_unshielded_offer
.as_ref()
.map_or(0, |offer| offer.inputs.len());
let registration_count = intent
.dust_actions
.as_ref()
.map_or(0, |da| da.registrations.len());
if guaranteed_signing_keys.len() != guaranteed_count {
return Err(WalletError::SigningFailed(format!(
"guaranteed signing keys count ({}) does not match guaranteed input count ({})",
guaranteed_signing_keys.len(),
guaranteed_count
)));
}
if fallible_signing_keys.len() != fallible_count {
return Err(WalletError::SigningFailed(format!(
"fallible signing keys count ({}) does not match fallible input count ({})",
fallible_signing_keys.len(),
fallible_count
)));
}
if dust_registration_signing_keys.len() != registration_count {
return Err(WalletError::SigningFailed(format!(
"dust registration signing keys count ({}) does not match registration count ({})",
dust_registration_signing_keys.len(),
registration_count
)));
}
intent
.sign(
rng,
segment_id,
guaranteed_signing_keys,
fallible_signing_keys,
dust_registration_signing_keys,
)
.map_err(|e| WalletError::SigningFailed(format!("Intent::sign: {e:?}")))
}
#[must_use]
pub fn build_dust_transaction(
intent: DustIntent,
segment_id: u16,
network_id: impl Into<String>,
) -> SignedDustTransaction {
let mut intents: StorageHashMap<u16, DustIntent, Db> = StorageHashMap::new();
intents = intents.insert(segment_id, intent);
Transaction::from_intents(network_id, intents)
}
pub fn serialize_signed_dust_transaction(tx: &SignedDustTransaction) -> Result<Vec<u8>> {
let mut bytes = Vec::with_capacity(2048);
tagged_serialize(tx, &mut bytes)
.map_err(|e| WalletError::Serialization(format!("tagged_serialize(signed): {e}")))?;
Ok(bytes)
}
pub fn finalize_dust_only_transaction(
tx: &SignedDustTransaction,
) -> Result<FinalizedDustTransaction> {
let post_prove = futures::executor::block_on(
tx.prove(NoopProvingProvider, &INITIAL_COST_MODEL),
)
.map_err(|e: TransactionProvingError<Db>| {
WalletError::Serialization(format!(
"finalize_dust_only_transaction: prove step failed — \
transaction must be registration-only (no spends, no contract \
calls, no Zswap offers); use finalize_with_proving_provider \
for spend-bearing transactions: {e:?}"
))
})?;
Ok(post_prove.seal(OsRng))
}
pub fn finalize_with_proving_provider<P>(
tx: &SignedDustTransaction,
prover: P,
) -> Result<FinalizedDustTransaction>
where
P: moonproof_ledger::transient_crypto::proofs::ProvingProvider,
{
let post_prove = futures::executor::block_on(tx.prove(prover, &INITIAL_COST_MODEL)).map_err(
|e: TransactionProvingError<Db>| {
WalletError::Serialization(format!(
"finalize_with_proving_provider: prove step failed: {e:?}"
))
},
)?;
Ok(post_prove.seal(OsRng))
}
pub fn serialize_finalized_dust_transaction(tx: &FinalizedDustTransaction) -> Result<Vec<u8>> {
let mut bytes = Vec::with_capacity(2048);
tagged_serialize(tx, &mut bytes).map_err(|e| {
WalletError::Serialization(format!("tagged_serialize(finalized dust): {e}"))
})?;
Ok(bytes)
}
fn build_self_transfer_offer(
inputs: &[crate::unshielded::UtxoWithMeta],
total_value: u128,
spender_verifying_key: &VerifyingKey,
) -> Option<UnshieldedOffer<Signature, Db>> {
if inputs.is_empty() {
return None;
}
let utxo_spends: Vec<UtxoSpend> = inputs
.iter()
.map(|u| UtxoSpend {
value: u.utxo.value,
owner: spender_verifying_key.clone(),
type_: NIGHT,
intent_hash: to_ledger_intent_hash(u.utxo.id.intent_hash),
output_no: u.utxo.id.output_no,
})
.collect();
let output = UtxoOutput {
value: total_value,
owner: UserAddress::from(spender_verifying_key.clone()),
type_: NIGHT,
};
Some(UnshieldedOffer {
inputs: utxo_spends.into(),
outputs: vec![output].into(),
signatures: Vec::<Signature>::new().into(),
})
}
#[must_use]
pub fn used_segment_ids<S, P, B>(tx: &Transaction<S, P, B, Db>) -> BTreeSet<u16>
where
S: moonproof_ledger::ledger::structure::SignatureKind<Db>,
P: moonproof_ledger::ledger::structure::ProofKind<Db>,
B: moonproof_ledger::ledger::structure::BindingKind<S, P, Db> + Storable<Db>,
{
match tx {
Transaction::Standard(stx) => stx.intents.keys().collect(),
Transaction::ClaimRewards(_) => BTreeSet::new(),
}
}
#[cfg(test)]
mod tests {
use super::*;
use moonproof_ledger::base_crypto::time::Duration;
use moonproof_ledger::ledger::dust::{DustParameters, DustSecretKey};
use rand::rngs::StdRng;
use rand::SeedableRng;
use crate::abstractions::NetworkId;
use crate::dust::state::DustState;
use crate::dust::transacting::{
build_dust_generation_recipe, DustBalancingRecipe, DustRegistrationSpec,
};
use crate::types::TokenType;
use crate::unshielded::ledger_adapter::signing_key_from_bytes;
use crate::unshielded::{UnshieldedUtxo, UtxoId, UtxoMeta, UtxoWithMeta};
fn dust_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(dust_params(), &sk, NetworkId::Undeployed)
}
fn signer() -> (SigningKey, VerifyingKey) {
let sk = signing_key_from_bytes(&[0x77u8; 32]).expect("signing key");
let vk = sk.verifying_key();
(sk, vk)
}
fn night_utxo(intent_byte: u8, value: u128) -> UtxoWithMeta {
UtxoWithMeta::new(
UnshieldedUtxo::new(
UtxoId::new([intent_byte; 32], 0),
value,
TokenType::new("native"),
[0u8; 32],
),
UtxoMeta::new(0, false),
)
}
#[test]
fn empty_recipe_yields_no_intent() {
let mut rng = StdRng::seed_from_u64(42);
let (_, vk) = signer();
let r = crate::dust::transacting::DustGenerationRecipe {
guaranteed_inputs: Vec::new(),
fallible_inputs: Vec::new(),
guaranteed_change_value: 0,
fallible_change_value: 0,
registration: DustRegistrationSpec {
dust_address: None,
allow_fee_payment: 0,
},
ctime: Timestamp::from_secs(10),
};
let intent =
build_dust_generation_intent(&r, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
assert!(intent.is_none());
}
#[test]
fn address_only_registration_yields_intent_without_offers() {
let s = empty_state();
let (_, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let recipe =
build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
.unwrap();
let intent =
build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
let intent = intent.expect("address-only registration is a valid intent");
assert!(intent.guaranteed_unshielded_offer.is_none());
assert!(intent.fallible_unshielded_offer.is_none());
let da = intent.dust_actions.expect("dust_actions populated");
assert_eq!(da.registrations.len(), 1);
assert_eq!(da.spends.len(), 0);
}
#[test]
fn registration_with_one_utxo_puts_input_in_guaranteed() {
let s = empty_state();
let (_, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let utxos = vec![night_utxo(0xAA, 150_000)];
let recipe = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
let intent =
build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
let intent = intent.unwrap();
let g = intent.guaranteed_unshielded_offer.unwrap();
assert_eq!(g.inputs.len(), 1);
assert_eq!(g.outputs.len(), 1);
let single_output = g.outputs.iter().next().unwrap().clone();
assert_eq!(single_output.value, 150_000);
assert!(intent.fallible_unshielded_offer.is_none());
}
#[test]
fn registration_with_multiple_utxos_splits_into_guaranteed_and_fallible() {
let s = empty_state();
let (_, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let utxos = vec![
night_utxo(0xAA, 100_000),
night_utxo(0xBB, 500_000),
night_utxo(0xCC, 200_000),
];
let recipe = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
let intent =
build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng).unwrap();
let intent = intent.unwrap();
let g = intent.guaranteed_unshielded_offer.unwrap();
let f = intent.fallible_unshielded_offer.unwrap();
assert_eq!(g.inputs.len(), 1, "guaranteed gets one (highest-yield)");
assert_eq!(f.inputs.len(), 2, "fallible gets the rest");
assert_eq!(g.outputs.len(), 1);
assert_eq!(f.outputs.len(), 1);
}
#[test]
fn sign_dust_intent_signs_a_real_registration_intent() {
let s = empty_state();
let (sk, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let utxos = vec![night_utxo(0xAA, 150_000)];
let recipe = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
.unwrap()
.unwrap();
let signed = sign_dust_intent(intent, 1, &sk, &mut rng).expect("sign ok");
assert!(
signed
.dust_actions
.unwrap()
.registrations
.iter()
.next()
.unwrap()
.signature
.is_some(),
"registration signature should be populated"
);
}
#[test]
fn sign_dust_intent_multi_rejects_mismatched_guaranteed_keys() {
let s = empty_state();
let (sk, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let utxos = vec![night_utxo(0xAA, 150_000)];
let recipe = build_dust_generation_recipe(
&s,
&utxos,
Some(s.public_key()),
Timestamp::from_secs(10),
)
.unwrap();
let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
.unwrap()
.unwrap();
let err = sign_dust_intent_multi(intent, 1, &[], &[], std::slice::from_ref(&sk), &mut rng)
.unwrap_err();
assert!(matches!(err, WalletError::SigningFailed(_)));
}
#[test]
fn sign_dust_intent_multi_rejects_mismatched_registration_keys() {
let s = empty_state();
let (_sk, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let recipe =
build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
.unwrap();
let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
.unwrap()
.unwrap();
let err = sign_dust_intent_multi(intent, 1, &[], &[], &[], &mut rng).unwrap_err();
assert!(matches!(err, WalletError::SigningFailed(_)));
}
#[test]
fn balancing_intent_with_no_spends_yields_none() {
let mut rng = StdRng::seed_from_u64(42);
let recipe = DustBalancingRecipe {
inputs: Vec::new(),
total_fee: 0,
};
let intent = build_dust_balancing_intent(
&recipe,
Vec::new(),
Timestamp::from_secs(10),
Timestamp::from_secs(20),
&mut rng,
)
.unwrap();
assert!(intent.is_none());
}
#[test]
fn finalize_dust_only_address_registration_round_trips() {
let s = empty_state();
let (sk, vk) = signer();
let mut rng = StdRng::seed_from_u64(42);
let recipe =
build_dust_generation_recipe(&s, &[], Some(s.public_key()), Timestamp::from_secs(10))
.unwrap();
let intent = build_dust_generation_intent(&recipe, &vk, Timestamp::from_secs(20), &mut rng)
.unwrap()
.unwrap();
let signed = sign_dust_intent(intent, 1, &sk, &mut rng).unwrap();
let tx = build_dust_transaction(signed, 1, "undeployed");
let finalized = finalize_dust_only_transaction(&tx).expect("finalize ok");
let bytes = serialize_finalized_dust_transaction(&finalized).expect("serialize ok");
assert!(
!bytes.is_empty(),
"finalized tx serializes to non-empty bytes"
);
}
}