moonproof-wallet 0.2.2

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
//! Helpers for replaying chain-side dust events into a [`DustState`].
//!
//! The indexer's `DustLedgerEvent.raw` field is a hex-encoded,
//! tagged-serialized [`Event<InMemoryDB>`]. This module wraps
//! deserialization + replay so callers don't need to import every
//! `moonproof_ledger::ledger::events` symbol.

use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::dust::{DustSecretKey, DustStateChanges};
use moonproof_ledger::ledger::events::Event;
use moonproof_ledger::serialize::tagged_deserialize;

use crate::dust::ledger_adapter::Db;
use crate::dust::state::DustState;
use crate::error::{Result, WalletError};

/// Decode a hex-encoded, tagged-serialized [`Event<InMemoryDB>`].
///
/// The hex string may carry an optional `0x` prefix.
pub fn decode_dust_event(hex_event: &str) -> Result<Event<Db>> {
    let bytes = moonproof_utils::parse_hex(hex_event)
        .map_err(|e| WalletError::DustReplay(format!("hex decode: {e}")))?;
    tagged_deserialize::<Event<Db>>(&mut bytes.as_slice())
        .map_err(|e| WalletError::DustReplay(format!("tagged_deserialize(Event): {e}")))
}

/// Decode a slice of hex events and replay them into the [`DustState`]
/// at the supplied `current_time`. Returns the updated state plus the
/// per-tx [`DustStateChanges`] reported by the underlying replay.
///
/// `current_time` should be the chain time at which TTLs are evaluated —
/// typically the block time at which the events landed (so any
/// `pending_until` timers from local spends are advanced correctly).
pub fn replay_hex_events(
    state: DustState,
    secret_key: &DustSecretKey,
    hex_events: impl IntoIterator<Item = impl AsRef<str>>,
    current_time: Timestamp,
) -> Result<(DustState, Vec<DustStateChanges>)> {
    let events: Vec<Event<Db>> = hex_events
        .into_iter()
        .map(|h| decode_dust_event(h.as_ref()))
        .collect::<Result<_>>()?;
    state.apply_events_with_changes(secret_key, events.iter(), current_time)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn decode_rejects_invalid_hex() {
        let err = decode_dust_event("not-hex!").unwrap_err();
        assert!(matches!(err, WalletError::DustReplay(_)));
    }

    #[test]
    fn decode_rejects_truncated_payload() {
        // Three bytes is way below the minimum tagged-Event length.
        let err = decode_dust_event("0xabcdef").unwrap_err();
        assert!(matches!(err, WalletError::DustReplay(_)));
    }

    #[test]
    fn replay_empty_event_list_is_a_noop() {
        use crate::abstractions::NetworkId;
        use moonproof_ledger::base_crypto::time::Duration;
        use moonproof_ledger::ledger::dust::DustParameters;

        let sk = DustSecretKey::derive_secret_key(&[0x42u8; 32]);
        let s = DustState::init_empty(
            DustParameters {
                night_dust_ratio: 1_000,
                generation_decay_rate: 1,
                dust_grace_period: Duration::from_secs(60),
            },
            &sk,
            NetworkId::Undeployed,
        );
        let (s2, changes) = replay_hex_events(
            s,
            &sk,
            std::iter::empty::<&str>(),
            Timestamp::from_secs(100),
        )
        .expect("empty replay never errors");
        assert!(changes.is_empty());
        assert_eq!(s2.pending_len(), 0);
    }
}