Skip to main content

midnight_ledger_v9/
dust.rs

1// This file is part of midnight-ledger.
2// Copyright (C) Midnight Foundation
3// SPDX-License-Identifier: Apache-2.0
4// Licensed under the Apache License, Version 2.0 (the "License");
5// You may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7// http://www.apache.org/licenses/LICENSE-2.0
8// Unless required by applicable law or agreed to in writing, software
9// distributed under the License is distributed on an "AS IS" BASIS,
10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11// See the License for the specific language governing permissions and
12// limitations under the License.
13
14use crate::error::{
15    DustLocalStateError, DustStateError, EventReplayError, MalformedTransaction, TransactionInvalid,
16};
17use crate::events::{Event, EventDetails};
18use crate::semantics::TransactionContext;
19use crate::structure::{
20    ErasedIntent, IntentHash, IntentSigningEnvelope, ProofKind, ProofMarker, ProofPreimageMarker,
21    SPECKS_PER_DUST, STARS_PER_NIGHT, SignatureKind, SignatureVerifyingKey, Symbol,
22    TransactionHash, UnshieldedOffer, Utxo, UtxoSpend, UtxoState,
23};
24use crate::utils::VecEnvelope;
25use crate::verify::{StateReference, WellFormedStrictness};
26use base_crypto::envelope::Envelope;
27use base_crypto::{
28    MemWrite,
29    hash::{HashOutput, PERSISTENT_HASH_BYTES, PersistentHashWriter, persistent_commit},
30    time::{Duration, Timestamp},
31};
32use base_crypto::{
33    data_provider::MidnightDataProvider,
34    fab::{Aligned, AlignedValue, Alignment, AlignmentAtom, AlignmentSegment, Value},
35};
36use coin_structure::coin::{NIGHT, UserAddress};
37use derive_where::derive_where;
38use futures::future::join_all;
39#[cfg(feature = "proof-verifying")]
40use lazy_static::lazy_static;
41use onchain_runtime::{
42    Cell_read, HistoricMerkleTree_check_root, HistoricMerkleTree_insert_hash, Set_insert,
43    ops::{Key, Op},
44    result_mode::ResultModeGather,
45    state::StateValue,
46};
47use rand::{CryptoRng, Rng};
48use serde::{Deserialize, Serialize};
49use serialize::{Deserializable, Serializable, Tagged, tag_enforcement_test};
50use std::error::Error;
51use std::fmt::{self, Debug, Display, Formatter};
52use std::marker::PhantomData;
53#[cfg(test)]
54use storage::db::InMemoryDB;
55use storage::{
56    Storable,
57    arena::{ArenaKey, Sp},
58    db::DB,
59    storable::Loader,
60    storage::{HashMap, HashSet, Identity, Map, TimeFilterMap},
61};
62use transient_crypto::commitment::Pedersen;
63use transient_crypto::curve::FR_BYTES;
64use transient_crypto::hash::{degrade_to_transient, transient_commit};
65use transient_crypto::merkle_tree::MerkleTreeCollapsedUpdate;
66use transient_crypto::proofs::{ProvingKeyMaterial, ProvingProvider};
67use transient_crypto::{
68    curve::Fr,
69    hash::{transient_hash, upgrade_from_transient},
70    merkle_tree,
71    merkle_tree::{MerkleTree, MerkleTreeDigest},
72    proofs::{KeyLocation, ProofPreimage, ProvingError, Resolver},
73    repr::FieldRepr,
74};
75use zeroize::{Zeroize, ZeroizeOnDrop};
76use zswap::verify::with_outputs;
77
78/// State slot indices of the `ledger` fields declared in `ledger/dust.compact`.
79///
80/// The on-chain runtime addresses contract state positionally, so each `ledger`
81/// declaration in the Compact source is reachable under `Key::Value(n)` where `n` is
82/// its zero-based declaration index. These constants are the single definition of
83/// that mapping; they are mirrored by hand, because the build consumes the
84/// pre-compiled ZKIR in `zkir-precompiles/` rather than invoking `compactc` (see
85/// `flake.nix`).
86///
87/// Reordering, inserting or removing a `ledger` declaration in `dust.compact`
88/// therefore requires updating these values in lockstep. Getting them wrong produces
89/// a public transcript that does not match the circuit's verifier key, so every
90/// affected dust proof fails to verify.
91mod compact_slots {
92    /// `ledger commitment_merkle_tree: HistoricMerkleTree<32, Field>`
93    pub(super) const DUST_IDX_COMMITMENT_TREE: u8 = 0;
94    /// `ledger generation_merkle_tree: HistoricMerkleTree<32, Field>`
95    pub(super) const DUST_IDX_GENERATION_TREE: u8 = 1;
96    /// `ledger nullifiers: Set<Field>`
97    pub(super) const DUST_IDX_NULLIFIERS: u8 = 2;
98    /// `ledger parameters: DustParameters`
99    pub(super) const DUST_IDX_PARAMETERS: u8 = 3;
100    /// `ledger ctime: Uint<64>`
101    pub(super) const DUST_IDX_CTIME: u8 = 4;
102    /// `ledger dust_spend: DustSpend`
103    pub(super) const DUST_IDX_SPEND: u8 = 5;
104
105    #[cfg(test)]
106    mod tests {
107        use super::*;
108
109        /// The `ledger` field names declared in a Compact source, in declaration order.
110        fn ledger_fields(src: &str) -> Vec<&str> {
111            src.lines()
112                .map(str::trim)
113                .map(|line| line.strip_prefix("export ").unwrap_or(line))
114                .filter_map(|line| line.strip_prefix("ledger "))
115                .map(|rest| rest.split(':').next().unwrap_or("").trim())
116                .collect()
117        }
118
119        /// Pins the constants above to the declaration order in `dust.compact`, so that
120        /// reordering, inserting, removing or renaming a `ledger` field there fails here
121        /// rather than silently invalidating every dust proof.
122        #[test]
123        fn slot_indices_match_compact_source() {
124            let fields = ledger_fields(include_str!("../dust.compact"));
125            let expected = [
126                (DUST_IDX_COMMITMENT_TREE, "commitment_merkle_tree"),
127                (DUST_IDX_GENERATION_TREE, "generation_merkle_tree"),
128                (DUST_IDX_NULLIFIERS, "nullifiers"),
129                (DUST_IDX_PARAMETERS, "parameters"),
130                (DUST_IDX_CTIME, "ctime"),
131                (DUST_IDX_SPEND, "dust_spend"),
132            ];
133            assert_eq!(
134                fields.len(),
135                expected.len(),
136                "dust.compact declares {} ledger fields, but {} slot indices are \
137                 defined in dust.rs; found {fields:?}",
138                fields.len(),
139                expected.len(),
140            );
141            for (idx, name) in expected {
142                assert_eq!(
143                    fields[usize::from(idx)],
144                    name,
145                    "slot {idx} is documented as `{name}`, but dust.compact declares \
146                     `{}` at that position",
147                    fields[usize::from(idx)],
148                );
149            }
150        }
151    }
152}
153use compact_slots::*;
154
155#[cfg(feature = "proof-verifying")]
156const SPEND_VK_RAW: &[u8] = include_bytes!("../static/dust/spend.verifier");
157
158#[cfg(feature = "proof-verifying")]
159lazy_static! {
160    pub static ref SPEND_VK: transient_crypto_old::proofs::VerifierKey =
161        serialize::tagged_deserialize(&mut SPEND_VK_RAW.to_vec().as_slice())
162            .expect("Dust Spend VK should be valid");
163}
164
165pub struct DustResolver(pub MidnightDataProvider);
166
167impl Resolver for DustResolver {
168    async fn resolve_key(&self, key: KeyLocation) -> std::io::Result<Option<ProvingKeyMaterial>> {
169        let file_root = match &*key.0 {
170            "midnight/dust/spend" => {
171                concat!("dust/", midnight_ledger_static::version!(), "/spend")
172            }
173            _ => return Ok(None),
174        };
175        fn read_to_vec(mut reader: impl std::io::Read) -> std::io::Result<Vec<u8>> {
176            let mut res = Vec::new();
177            reader.read_to_end(&mut res)?;
178            Ok(res)
179        }
180        let prover_key = read_to_vec(
181            &mut self
182                .0
183                .get_file(
184                    &format!("{file_root}.prover"),
185                    &format!("failed to find built-in dust prover key {file_root}.prover"),
186                )
187                .await?,
188        )?;
189        let verifier_key = read_to_vec(
190            &mut self
191                .0
192                .get_file(
193                    &format!("{file_root}.verifier"),
194                    &format!("failed to find built-in dust verifier key {file_root}.verifier"),
195                )
196                .await?,
197        )?;
198        let ir_source = read_to_vec(
199            &mut self
200                .0
201                .get_file(
202                    &format!("{file_root}.bzkir"),
203                    &format!("failed to find built-in dust IR {file_root}.bzkir"),
204                )
205                .await?,
206        )?;
207        Ok(Some(ProvingKeyMaterial {
208            ir_source,
209            prover_key,
210            verifier_key,
211        }))
212    }
213}
214
215const DUST_COMMITMENT_TREE_DEPTH: u8 = 32;
216const DUST_GENERATION_TREE_DEPTH: u8 = 32;
217
218#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
219#[storable(base)]
220#[tag = "dust-nullifier[v1]"]
221pub struct DustNullifier(pub Fr);
222tag_enforcement_test!(DustNullifier);
223
224#[derive(Debug, Copy, Clone, Hash, PartialEq, Eq, Serializable, Storable, FieldRepr)]
225#[storable(base)]
226#[tag = "dust-commitment[v1]"]
227pub struct DustCommitment(pub Fr);
228tag_enforcement_test!(DustCommitment);
229
230impl From<DustCommitment> for HashOutput {
231    fn from(com: DustCommitment) -> HashOutput {
232        upgrade_from_transient(com.0)
233    }
234}
235
236impl From<HashOutput> for DustCommitment {
237    fn from(value: HashOutput) -> Self {
238        DustCommitment(degrade_to_transient(value))
239    }
240}
241
242pub type Seed = [u8; 32];
243
244#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
245#[storable(base)]
246#[tag = "dust-public-key[v1]"]
247pub struct DustPublicKey(pub Fr);
248tag_enforcement_test!(DustPublicKey);
249
250#[derive(Clone, Serializable, Storable, FieldRepr, Zeroize, ZeroizeOnDrop)]
251#[storable(base)]
252#[tag = "dust-secret-key[v1]"]
253pub struct DustSecretKey(pub Fr);
254tag_enforcement_test!(DustSecretKey);
255
256impl Debug for DustSecretKey {
257    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
258        f.write_str("<dust secret key>")
259    }
260}
261
262impl From<DustSecretKey> for DustPublicKey {
263    fn from(sk: DustSecretKey) -> DustPublicKey {
264        DustPublicKey(transient_hash(&[b"mdn:dust:pk".field_vec()[0], sk.0]))
265    }
266}
267
268impl DustSecretKey {
269    pub fn sample(rng: &mut (impl Rng + CryptoRng)) -> Self {
270        DustSecretKey(rng.r#gen())
271    }
272
273    pub fn nonces(&self, initial_nonce: InitialNonce) -> impl Iterator<Item = Fr> + use<'_> {
274        let pk = DustPublicKey::from(self.clone());
275        (0u32..).map(move |seq| {
276            transient_hash(&(initial_nonce, seq, if seq == 0 { pk.0 } else { self.0 }).field_vec())
277        })
278    }
279
280    pub fn derive_secret_key(seed: &Seed) -> Self {
281        const DOMAIN_SEPARATOR: &[u8; 12] = b"midnight:dsk";
282        const NUMBER_OF_BYTES: usize = 64;
283        let raw_bytes = DustSecretKey::sample_bytes(seed, NUMBER_OF_BYTES, DOMAIN_SEPARATOR);
284        let raw_bytes_arr: [u8; 64] = raw_bytes.clone().try_into().unwrap();
285        DustSecretKey(Fr::from_uniform_bytes(&raw_bytes_arr))
286    }
287
288    pub fn sample_bytes(seed: &Seed, no_of_bytes: usize, domain_separator: &[u8]) -> Vec<u8> {
289        let hash_bytes = PERSISTENT_HASH_BYTES;
290        let rounds = no_of_bytes.div_ceil(hash_bytes);
291        let mut res: Vec<u8> = Vec::new();
292        for round in 0..rounds {
293            let mut outer_writer = PersistentHashWriter::new();
294            MemWrite::write(&mut outer_writer, domain_separator);
295            MemWrite::write(&mut outer_writer, &{
296                let mut inner_writer = PersistentHashWriter::new();
297                MemWrite::write(&mut inner_writer, &((round as u64).to_le_bytes()));
298                MemWrite::write(&mut inner_writer, seed);
299                inner_writer.finalize().0
300            });
301            let round_hash = outer_writer.finalize();
302            let bytes_to_add = hash_bytes.min(no_of_bytes - round * 32);
303            res.extend_from_slice(&round_hash.0[0..bytes_to_add])
304        }
305        res
306    }
307
308    pub fn repr(&self) -> Vec<u8> {
309        self.0.as_le_bytes()
310    }
311}
312
313#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
314#[storable(base)]
315#[tag = "dust-initial-nonce[v1]"]
316pub struct InitialNonce(pub HashOutput);
317tag_enforcement_test!(InitialNonce);
318
319pub fn initial_nonce(output_no: u32, intent_hash: IntentHash) -> InitialNonce {
320    InitialNonce(persistent_commit(&output_no, intent_hash.0))
321}
322
323impl UtxoSpend {
324    pub fn initial_nonce(&self) -> InitialNonce {
325        initial_nonce(self.output_no, self.intent_hash)
326    }
327}
328
329impl Utxo {
330    pub fn initial_nonce(&self) -> InitialNonce {
331        initial_nonce(self.output_no, self.intent_hash)
332    }
333}
334
335pub fn dust_nonce(initial_nonce: &InitialNonce, seq: u32, sk: &DustSecretKey) -> Fr {
336    transient_hash((*initial_nonce, seq, sk.0).field_vec().as_ref())
337}
338
339pub fn dust_first_nonce(initial_nonce: &InitialNonce, dust_addr: &DustPublicKey) -> Fr {
340    transient_hash((*initial_nonce, 0u32, *dust_addr).field_vec().as_ref())
341}
342
343#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
344#[storable(base)]
345#[tag = "dust-output[v1]"]
346pub struct DustOutput {
347    pub initial_value: u128,
348    pub owner: DustPublicKey,
349    pub nonce: Fr,
350    pub seq: u32,
351    pub ctime: Timestamp,
352}
353tag_enforcement_test!(DustOutput);
354
355impl DustOutput {
356    pub fn updated_value(
357        &self,
358        gen_info: &DustGenerationInfo,
359        now: Timestamp,
360        params: &DustParameters,
361    ) -> u128 {
362        // There are up to four linear segments:
363        // 1. Generating (from inp.ctime to tfull, the time dust fills to the cap)
364        // 2. Constant full (from tfull to gen.dtime)
365        // 3. Decaying (from gen.dtime to tempty, the time dust reaches zero)
366        // 4. Constant empty (from tempty onwards)
367        //
368        // If gen.dtime <= tfull, phase 2 doesn't occur.
369        // If gen.dtime <= inp.ctime Phases 1 and 2 do not occur.
370        //
371        // The maximum capacity is gen.value * night_dust_ratio.
372        let vfull = gen_info
373            .value
374            .saturating_mul(params.night_dust_ratio as u128);
375        // The slope of generation and decay for a specific dust UTXO
376        // is proportional to the value of its backing night.
377        let rate = gen_info
378            .value
379            .saturating_mul(params.generation_decay_rate as u128);
380        // Note that we aren't constraining the end to be after the start, instead
381        // we're clamping the output to the reasonable region of outputs.
382        let tstart_phase_1 = self.ctime;
383        let tend_phase_12 = Timestamp::min(gen_info.dtime, now);
384        let dt_phase_12 = (tend_phase_12 - tstart_phase_1).as_seconds();
385        let dt_phase_12 = if dt_phase_12 >= 0 {
386            dt_phase_12 as u128
387        } else {
388            0
389        };
390        let value_phase_1_unchecked = dt_phase_12
391            .saturating_mul(rate)
392            .saturating_add(self.initial_value);
393        let value_phase_12 = u128::min(value_phase_1_unchecked, vfull);
394        // Again, we aren't constraining the end to be after the start, instead
395        // we're clamping the output to the reasonable region of outputs.
396        let tstart_phase_3 = gen_info.dtime;
397        let tend_phase_3 = now;
398        let dt_phase_3 = (tend_phase_3 - tstart_phase_3).as_seconds();
399        let dt_phase_3 = if dt_phase_3 >= 0 {
400            dt_phase_3 as u128
401        } else {
402            0
403        };
404        value_phase_12.saturating_sub(dt_phase_3.saturating_mul(rate))
405    }
406
407    pub fn commitment(&self) -> DustCommitment {
408        DustPreProjection {
409            initial_value: self.initial_value,
410            owner: self.owner,
411            nonce: self.nonce,
412            ctime: self.ctime,
413        }
414        .commitment()
415    }
416}
417
418#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable)]
419#[storable(base)]
420#[tag = "qualified-dust-output[v1]"]
421pub struct QualifiedDustOutput {
422    pub initial_value: u128,
423    pub owner: DustPublicKey,
424    pub nonce: Fr,
425    pub seq: u32,
426    pub ctime: Timestamp,
427    pub backing_night: InitialNonce,
428    pub mt_index: u64,
429}
430tag_enforcement_test!(QualifiedDustOutput);
431
432impl QualifiedDustOutput {
433    pub fn commitment(&self) -> DustCommitment {
434        DustPreProjection {
435            initial_value: self.initial_value,
436            owner: self.owner,
437            nonce: self.nonce,
438            ctime: self.ctime,
439        }
440        .commitment()
441    }
442
443    pub fn nullifier(&self, sk: &DustSecretKey) -> DustNullifier {
444        DustPreProjection {
445            initial_value: self.initial_value,
446            owner: sk.clone(),
447            nonce: self.nonce,
448            ctime: self.ctime,
449        }
450        .nullifier()
451    }
452}
453
454impl From<QualifiedDustOutput> for DustOutput {
455    fn from(value: QualifiedDustOutput) -> Self {
456        DustOutput {
457            initial_value: value.initial_value,
458            owner: value.owner,
459            nonce: value.nonce,
460            seq: value.seq,
461            ctime: value.ctime,
462        }
463    }
464}
465
466#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
467#[storable(base)]
468#[tag = "dust-pre-projection[v1]"]
469pub struct DustPreProjection<T: Serializable + Deserializable + Clone + Sync + Send + 'static> {
470    pub initial_value: u128,
471    pub owner: T,
472    pub nonce: Fr,
473    pub ctime: Timestamp,
474}
475tag_enforcement_test!(DustPreProjection<DustPublicKey>);
476
477impl DustPreProjection<DustPublicKey> {
478    pub fn commitment(&self) -> DustCommitment {
479        DustCommitment(transient_commit(
480            &self.field_vec(),
481            b"mdn:dust:cm".field_vec()[0],
482        ))
483    }
484}
485
486impl DustPreProjection<DustSecretKey> {
487    pub fn nullifier(&self) -> DustNullifier {
488        DustNullifier(transient_commit(
489            &self.field_vec(),
490            b"mdn:dust:nul".field_vec()[0],
491        ))
492    }
493}
494
495#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, FieldRepr)]
496#[storable(base)]
497#[tag = "dust-generation-info[v1]"]
498pub struct DustGenerationInfo {
499    pub value: u128,
500    pub owner: DustPublicKey,
501    pub nonce: InitialNonce,
502    pub dtime: Timestamp,
503}
504tag_enforcement_test!(DustGenerationInfo);
505
506pub(crate) const DUST_GENERATION_INFO_SIZE: usize = 16 + FR_BYTES + PERSISTENT_HASH_BYTES + 8;
507
508impl DustGenerationInfo {
509    pub fn merkle_hash(&self) -> HashOutput {
510        upgrade_from_transient(transient_hash(&self.field_vec()[..]))
511    }
512}
513
514/// Deprecated. Retained only to preserve the serialized shape of
515/// [`DustGenerationState`] (`dust-generation-state[v1]`) so that pre-patch wasm
516/// libraries can still deserialize ledger state produced by patched binaries.
517///
518/// It is no longer consulted for soundness: generation uniqueness is now enforced
519/// via [`DustGenerationState::night_indices`], which keys on the initial nonce
520/// alone (the spend circuit binds `gen.nonce` to that nonce). Do not reintroduce
521/// this into any validity check.
522#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable)]
523#[storable(base)]
524#[tag = "dust-generation-uniqueness-info"]
525pub struct DustGenerationUniquenessInfo {
526    pub value: u128,
527    pub owner: DustPublicKey,
528    pub nonce: InitialNonce,
529}
530tag_enforcement_test!(DustGenerationUniquenessInfo);
531
532impl From<DustGenerationInfo> for DustGenerationUniquenessInfo {
533    fn from(info: DustGenerationInfo) -> DustGenerationUniquenessInfo {
534        DustGenerationUniquenessInfo {
535            value: info.value,
536            owner: info.owner,
537            nonce: info.nonce,
538        }
539    }
540}
541
542#[derive(Storable)]
543#[derive_where(Clone, PartialEq, Eq; P)]
544#[storable(db = D)]
545#[tag = "dust-spend[v1]"]
546pub struct DustSpend<P: ProofKind<D>, D: DB> {
547    pub v_fee: u128,
548    pub old_nullifier: DustNullifier,
549    pub new_commitment: DustCommitment,
550    pub proof: P::LatestProof,
551}
552tag_enforcement_test!(DustSpend<(), InMemoryDB>);
553
554impl<P: ProofKind<D>, D: DB> Debug for DustSpend<P, D> {
555    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
556        f.debug_struct("DustSpend")
557            .field("v_fee", &self.v_fee)
558            .field("old_nullifier", &Symbol("<dust nullifier>"))
559            .field("new_commitment", &Symbol("<dust commitment>"))
560            .field("proof", &Symbol("<proof>"))
561            .finish()
562    }
563}
564
565impl<P: ProofKind<D>, D: DB> FieldRepr for DustSpend<P, D> {
566    fn field_repr<W: MemWrite<Fr>>(&self, writer: &mut W) {
567        self.v_fee.field_repr(writer);
568        self.old_nullifier.field_repr(writer);
569        self.new_commitment.field_repr(writer);
570    }
571    fn field_size(&self) -> usize {
572        self.v_fee.field_size() + self.old_nullifier.field_size() + self.new_commitment.field_size()
573    }
574}
575
576impl<P: ProofKind<D>, D: DB> Aligned for DustSpend<P, D> {
577    fn alignment() -> Alignment {
578        Alignment(vec![
579            AlignmentSegment::Atom(AlignmentAtom::Bytes { length: 16 }),
580            AlignmentSegment::Atom(AlignmentAtom::Field),
581            AlignmentSegment::Atom(AlignmentAtom::Field),
582        ])
583    }
584}
585
586impl<P: ProofKind<D>, D: DB> From<DustSpend<P, D>> for Value {
587    fn from(spend: DustSpend<P, D>) -> Value {
588        Value(vec![
589            spend.v_fee.into(),
590            spend.old_nullifier.0.into(),
591            spend.new_commitment.0.into(),
592        ])
593    }
594}
595
596impl<D: DB> DustSpend<ProofPreimageMarker, D> {
597    async fn prove(
598        &self,
599        prover: impl ProvingProvider,
600        segment_id: u16,
601        binding: Pedersen,
602    ) -> Result<DustSpend<ProofMarker, D>, ProvingError> {
603        let proof = prover
604            .prove(
605                &self.proof,
606                Some(transient_hash(
607                    &(
608                        Fr::from_le_bytes(b"midnight:dust:proof"),
609                        segment_id,
610                        binding,
611                    )
612                        .field_vec(),
613                )),
614            )
615            .await?;
616        Ok(DustSpend {
617            v_fee: self.v_fee,
618            old_nullifier: self.old_nullifier,
619            new_commitment: self.new_commitment,
620            proof,
621        })
622    }
623}
624
625impl<P: ProofKind<D>, D: DB> DustSpend<P, D> {
626    pub(crate) fn erase_proofs(&self) -> DustSpend<(), D> {
627        DustSpend {
628            v_fee: self.v_fee,
629            old_nullifier: self.old_nullifier,
630            new_commitment: self.new_commitment,
631            proof: (),
632        }
633    }
634
635    #[cfg(not(feature = "proof-verifying"))]
636    pub(crate) fn well_formed(
637        &self,
638        _state_ref: &impl StateReference<D>,
639        _segment_id: u16,
640        _binding: Pedersen,
641        _strictness: WellFormedStrictness,
642        _ctime: Timestamp,
643    ) -> Result<(), MalformedTransaction<D>> {
644        Ok(())
645    }
646
647    #[cfg(feature = "proof-verifying")]
648    pub(crate) fn well_formed(
649        &self,
650        state_ref: &impl StateReference<D>,
651        segment_id: u16,
652        binding: Pedersen,
653        strictness: WellFormedStrictness,
654        ctime: Timestamp,
655    ) -> Result<(), MalformedTransaction<D>> {
656        if strictness.verify_native_proofs {
657            state_ref.dust_spend_check(ctime, |params, commitment_root, generation_root| {
658                let mut prog = Vec::new();
659                // Check commitment merkle tree root
660                prog.extend::<[Op<ResultModeGather, D>; 6]>(HistoricMerkleTree_check_root!(
661                    [Key::Value(DUST_IDX_COMMITMENT_TREE.into())],
662                    false,
663                    32,
664                    Fr,
665                    commitment_root.0
666                ));
667                // Check generation merkle tree root
668                prog.extend(HistoricMerkleTree_check_root!(
669                    [Key::Value(DUST_IDX_GENERATION_TREE.into())],
670                    false,
671                    32,
672                    Fr,
673                    generation_root.0
674                ));
675                // Read spend
676                prog.extend(Cell_read!(
677                    [Key::Value(DUST_IDX_SPEND.into())],
678                    false,
679                    DustSpend
680                ));
681                // Read ctime
682                prog.extend(Cell_read!([Key::Value(DUST_IDX_CTIME.into())], false, u64));
683                // Read dust parameters
684                prog.extend(Cell_read!(
685                    [Key::Value(DUST_IDX_PARAMETERS.into())],
686                    false,
687                    DustParameters
688                ));
689                // Insert old nullifier
690                prog.extend(Set_insert!(
691                    [Key::Value(DUST_IDX_NULLIFIERS.into())],
692                    false,
693                    Fr,
694                    self.old_nullifier.0
695                ));
696                // Read ctime
697                prog.extend(Cell_read!([Key::Value(DUST_IDX_CTIME.into())], false, u64));
698                // Insert new commitment
699                prog.extend(HistoricMerkleTree_insert_hash!(
700                    [Key::Value(DUST_IDX_COMMITMENT_TREE.into())],
701                    false,
702                    32,
703                    Fr,
704                    HashOutput::from(self.new_commitment)
705                ));
706
707                let mut pis = vec![];
708                pis.push(transient_hash(
709                    &(
710                        Fr::from_le_bytes(b"midnight:dust:proof"),
711                        segment_id,
712                        binding,
713                    )
714                        .field_vec(),
715                ));
716                for op in with_outputs(
717                    prog.into_iter(),
718                    [
719                        true.into(),         // commitment root check
720                        true.into(),         // nullifier root check
721                        self.clone().into(), // dust spend read
722                        ctime.into(),        // ctime read
723                        params.into(),       // parameter read
724                        ctime.into(),        // ctime read
725                    ]
726                    .into_iter(),
727                ) {
728                    op.field_repr(&mut pis);
729                }
730                debug_assert_eq!(pis.len(), DUST_SPEND_PIS);
731                let mut dust_op = onchain_runtime::state::ContractOperation::new(None, None);
732                dust_op.v2 = Some(SPEND_VK.clone());
733                let dust_call = crate::structure::ContractCall {
734                    address: coin_structure::contract::ContractAddress::default(),
735                    entry_point: onchain_runtime::state::EntryPointBuf(vec![]),
736                    guaranteed_transcript: None,
737                    fallible_transcript: None,
738                    communication_commitment: Fr::default(),
739                    proof: self.proof.clone().into(),
740                };
741                P::proof_verify(
742                    &dust_op,
743                    &self.proof.clone().into(),
744                    pis,
745                    &dust_call,
746                    strictness.proof_verification_mode,
747                )
748                .map_err(|_| MalformedTransaction::InvalidDustSpendProof {
749                    declared_time: ctime,
750                    dust_spend: Box::new(self.erase_proofs()),
751                })
752            })
753        } else {
754            Ok(())
755        }
756    }
757}
758
759#[derive(Storable, Envelope)]
760#[derive_where(Clone, PartialEq, Eq, Debug; S)]
761#[storable(db = D)]
762#[envelope(DustRegistrationSigningEnvelope<S, D>)]
763#[tag = "dust-registration[v2]"]
764pub struct DustRegistration<S: SignatureKind<D>, D: DB> {
765    pub night_key: SignatureVerifyingKey,
766    pub dust_address: Option<Sp<DustPublicKey, D>>,
767    pub allow_fee_payment: u128,
768    #[allow(clippy::type_complexity)]
769    pub signature: Option<Sp<S::Signature<IntentSigningEnvelope<D>>, D>>,
770}
771tag_enforcement_test!(DustRegistration<(), InMemoryDB>);
772
773#[derive(Serializable)]
774#[tag = "dust-registration-signing-envelope[v8]"]
775#[phantom(D)]
776pub struct DustRegistrationSigningEnvelope<S: SignatureKind<D>, D: DB> {
777    pub night_key: SignatureVerifyingKey,
778    pub dust_address: Option<Sp<DustPublicKey, D>>,
779    pub allow_fee_payment: u128,
780    #[allow(clippy::type_complexity)]
781    pub signature: PhantomData<Option<Sp<S::Signature<IntentSigningEnvelope<D>>, D>>>,
782}
783tag_enforcement_test!(DustRegistrationSigningEnvelope<(), InMemoryDB>);
784
785impl<S: SignatureKind<D>, D: DB> DustRegistration<S, D> {
786    pub(crate) fn erase_signatures(&self) -> DustRegistration<(), D> {
787        DustRegistration {
788            night_key: self.night_key.clone(),
789            dust_address: self.dust_address.clone(),
790            allow_fee_payment: self.allow_fee_payment,
791            signature: self.signature.as_ref().map(|_| Sp::new(())),
792        }
793    }
794
795    pub(crate) fn well_formed<'d>(
796        &self,
797        data_to_sign: impl FnOnce() -> &'d [u8],
798        strictness: WellFormedStrictness,
799    ) -> Result<(), MalformedTransaction<D>> {
800        if !strictness.verify_signatures
801            || self
802                .signature
803                .as_ref()
804                .map(|sig| S::signature_verify(data_to_sign(), self.night_key.clone(), sig))
805                == Some(true)
806        {
807            Ok(())
808        } else {
809            warn!(registration = ?self, "signature verification of dust registration failed");
810            Err(MalformedTransaction::InvalidDustRegistrationSignature {
811                registration: Box::new(self.erase_signatures()),
812            })
813        }
814    }
815}
816
817#[derive(Storable, Envelope)]
818#[derive_where(Debug)]
819#[derive_where(Clone, PartialEq, Eq; S, P)]
820#[storable(db = D)]
821#[envelope(DustActionsSigningEnvelope<S, P, D>)]
822#[tag = "dust-actions[v2]"]
823pub struct DustActions<S: SignatureKind<D>, P: ProofKind<D>, D: DB> {
824    pub spends: storage::storage::Array<DustSpend<P, D>, D>,
825    pub registrations: storage::storage::Array<DustRegistration<S, D>, D>,
826    pub ctime: Timestamp,
827}
828tag_enforcement_test!(DustActions<(), (), InMemoryDB>);
829
830#[derive(Serializable)]
831#[tag = "dust-actions-signing-envelope[v2]"]
832#[phantom(D)]
833pub struct DustActionsSigningEnvelope<S: SignatureKind<D>, P: ProofKind<D>, D: DB> {
834    pub spends: storage::storage::Array<DustSpend<P, D>, D>,
835    pub registrations: VecEnvelope<DustRegistrationSigningEnvelope<S, D>>,
836    pub ctime: Timestamp,
837}
838tag_enforcement_test!(DustActionsSigningEnvelope<(), (), InMemoryDB>);
839
840impl<S: SignatureKind<D>, D: DB> DustActions<S, ProofPreimageMarker, D> {
841    pub(crate) async fn prove(
842        &self,
843        mut prover: impl ProvingProvider,
844        segment_id: u16,
845        binding: Pedersen,
846    ) -> Result<DustActions<S, ProofMarker, D>, ProvingError> {
847        let spends = join_all(
848            self.spends
849                .iter_deref()
850                .map(|spend| spend.prove(prover.split(), segment_id, binding)),
851        )
852        .await;
853        Ok(DustActions {
854            spends: spends.into_iter().collect::<Result<_, _>>()?,
855            registrations: self.registrations.clone(),
856            ctime: self.ctime,
857        })
858    }
859}
860
861impl<S: SignatureKind<D>, P: ProofKind<D>, D: DB> DustActions<S, P, D> {
862    pub(crate) fn erase_proofs(&self) -> DustActions<S, (), D> {
863        DustActions {
864            spends: self
865                .spends
866                .iter_deref()
867                .map(DustSpend::erase_proofs)
868                .collect(),
869            registrations: self.registrations.clone(),
870            ctime: self.ctime,
871        }
872    }
873
874    pub(crate) fn erase_signatures(&self) -> DustActions<(), P, D> {
875        DustActions {
876            spends: self.spends.clone(),
877            registrations: self
878                .registrations
879                .iter_deref()
880                .map(DustRegistration::erase_signatures)
881                .collect(),
882            ctime: self.ctime,
883        }
884    }
885
886    pub(crate) fn well_formed(
887        &self,
888        ref_state: &impl StateReference<D>,
889        strictness: WellFormedStrictness,
890        segment_id: u16,
891        parent: &ErasedIntent<D>,
892        tblock: Timestamp,
893    ) -> Result<(), MalformedTransaction<D>> {
894        let binding = parent.binding_commitment;
895        if self.spends.is_empty() && self.registrations.is_empty() {
896            warn!("non-canonical dust actions: empty");
897            return Err(MalformedTransaction::NotNormalized);
898        }
899        for spend in self.spends.iter() {
900            spend.well_formed(ref_state, segment_id, binding, strictness, self.ctime)?;
901        }
902        // Every registration signs the whole intent, so it is serialized once.
903        let data_to_sign = std::cell::OnceCell::new();
904        for reg in self.registrations.iter() {
905            ref_state.stateless_check(|| {
906                reg.well_formed(
907                    || data_to_sign.get_or_init(|| parent.data_to_sign(segment_id)),
908                    strictness,
909                )
910            })?;
911        }
912        ref_state.param_check(true, |params| if self.ctime > tblock || self.ctime + params.dust.dust_grace_period < tblock {
913            warn!(ctime = ?self.ctime, ?tblock, grace_period = ?params.dust.dust_grace_period, "dust actions out of TTL range");
914            Err(MalformedTransaction::OutOfDustValidityWindow {
915                dust_ctime: self.ctime,
916                // NOTE: our subtraction impl is saturating, that's fine here.
917                validity_start: tblock - params.dust.dust_grace_period,
918                validity_end: tblock,
919            })
920        } else {
921            Ok(())
922        })?;
923        ref_state.stateless_check(|| {
924            // Make sure that we are not registering for the same night key more than once
925            let mut night_keys = self.registrations.iter_deref().map(|reg| &reg.night_key).collect::<Vec<_>>();
926            night_keys.sort();
927            if let Some(window) = night_keys.windows(2).find(|window| window[0] == window[1]) {
928                warn!(key = ?window[0], "non-canonical dust actions: multiple registrations for same key");
929                return Err(MalformedTransaction::MultipleDustRegistrationsForKey {
930                    key: window[0].clone(),
931                });
932            }
933            Ok(())
934        })?;
935        // Make sure that each registration has sufficient unclaimed night in the ref utxo state to
936        // cover its allowed fee payment field.
937        if strictness.enforce_balancing {
938            self.registrations
939                .iter()
940                .filter(|reg| reg.allow_fee_payment > 0)
941                .try_for_each(|reg| {
942                    ref_state.generationless_fee_availability_check(
943                        parent,
944                        &reg.night_key,
945                        |available| {
946                            if available < reg.allow_fee_payment {
947                                warn!(
948                                    ?available,
949                                    ?reg,
950                                    "insufficient fees to cover registration fee allowance"
951                                );
952                                Err(MalformedTransaction::InsufficientDustForRegistrationFee {
953                                    registration: Box::new(reg.erase_signatures()),
954                                    available_dust: available,
955                                })
956                            } else {
957                                Ok(())
958                            }
959                        },
960                    )
961                })?;
962        }
963        Ok(())
964    }
965}
966
967#[derive(Debug, Copy, Clone, PartialEq, Eq, Serializable, Storable, Serialize, Deserialize)]
968#[storable(base)]
969#[tag = "dust-parameters[v1]"]
970pub struct DustParameters {
971    pub night_dust_ratio: u64,
972    pub generation_decay_rate: u32,
973    pub dust_grace_period: Duration,
974}
975tag_enforcement_test!(DustParameters);
976
977impl DustParameters {
978    pub const fn time_to_cap(&self) -> Duration {
979        // Should not happen, but panic-guards
980        if self.generation_decay_rate == 0 {
981            Duration::from_secs(i128::MAX)
982        } else {
983            Duration::from_secs(
984                self.night_dust_ratio
985                    .div_ceil(self.generation_decay_rate as u64) as i128,
986            )
987        }
988    }
989}
990
991impl FieldRepr for DustParameters {
992    fn field_repr<W: MemWrite<Fr>>(&self, writer: &mut W) {
993        let grace_period_secs = self.dust_grace_period.as_seconds();
994        let grace_period_u32 = i128::clamp(grace_period_secs, 0, u32::MAX as i128) as u32;
995        self.night_dust_ratio.field_repr(writer);
996        self.generation_decay_rate.field_repr(writer);
997        grace_period_u32.field_repr(writer);
998    }
999    fn field_size(&self) -> usize {
1000        3
1001    }
1002}
1003
1004impl Aligned for DustParameters {
1005    fn alignment() -> Alignment {
1006        Alignment(vec![
1007            AlignmentSegment::Atom(AlignmentAtom::Bytes { length: 8 }),
1008            AlignmentSegment::Atom(AlignmentAtom::Bytes { length: 4 }),
1009            AlignmentSegment::Atom(AlignmentAtom::Bytes { length: 4 }),
1010        ])
1011    }
1012}
1013
1014impl From<DustParameters> for Value {
1015    fn from(params: DustParameters) -> Value {
1016        let grace_period_secs = params.dust_grace_period.as_seconds();
1017        let grace_period_u32 = i128::clamp(grace_period_secs, 0, u32::MAX as i128) as u32;
1018        Value(vec![
1019            params.night_dust_ratio.into(),
1020            params.generation_decay_rate.into(),
1021            grace_period_u32.into(),
1022        ])
1023    }
1024}
1025
1026#[derive(Storable)]
1027#[derive_where(Clone, Debug, PartialEq, Eq)]
1028#[storable(db = D)]
1029#[tag = "dust-utxo-state[v1]"]
1030#[must_use]
1031pub struct DustUtxoState<D: DB> {
1032    pub commitments: MerkleTree<(), D>,
1033    pub commitments_first_free: u64,
1034    pub nullifiers: HashSet<DustNullifier, D>,
1035    pub root_history: TimeFilterMap<Identity<MerkleTreeDigest>, D>,
1036}
1037tag_enforcement_test!(DustUtxoState<InMemoryDB>);
1038
1039impl<D: DB> Default for DustUtxoState<D> {
1040    fn default() -> Self {
1041        DustUtxoState {
1042            commitments: MerkleTree::blank(DUST_COMMITMENT_TREE_DEPTH),
1043            commitments_first_free: 0,
1044            nullifiers: HashSet::default(),
1045            root_history: TimeFilterMap::new(),
1046        }
1047    }
1048}
1049
1050#[derive(Storable)]
1051#[derive_where(Clone, Debug, PartialEq, Eq)]
1052#[storable(db = D)]
1053#[tag = "dust-generation-state[v1]"]
1054#[must_use]
1055pub struct DustGenerationState<D: DB> {
1056    pub address_delegation: Map<UserAddress, DustPublicKey, D>,
1057    pub generating_tree: MerkleTree<DustGenerationInfo, D>,
1058    pub generating_tree_first_free: u64,
1059    /// Deprecated. No longer populated or consulted; retained solely to preserve
1060    /// the serialized shape of this struct (`dust-generation-state[v1]`) for
1061    /// pre-patch wasm libraries. Soundness now relies on `night_indices` below.
1062    /// See [`DustGenerationUniquenessInfo`].
1063    pub generating_set: HashSet<DustGenerationUniquenessInfo, D>,
1064    /// Maps each generation's initial nonce to its index in `generating_tree`.
1065    ///
1066    /// This map MUST be append-only: a nonce, once inserted, is never removed.
1067    /// Dust-spend soundness depends on it — `fresh_dust_output` uses it to reject
1068    /// a second generation reusing an existing initial nonce, and the spend circuit
1069    /// binds `gen.nonce` to the spent UTXO's initial nonce. If an entry could be
1070    /// dropped, a nonce could recur with a different value and the binding would no
1071    /// longer uniquely determine the generation. (Contrast `DustLocalState`'s own
1072    /// `night_indices`, which is wallet-local and safe to prune in `process_ttls`.)
1073    pub night_indices: HashMap<InitialNonce, u64, D>,
1074    pub root_history: TimeFilterMap<Identity<MerkleTreeDigest>, D>,
1075}
1076tag_enforcement_test!(DustGenerationState<InMemoryDB>);
1077
1078impl<D: DB> Default for DustGenerationState<D> {
1079    fn default() -> Self {
1080        DustGenerationState {
1081            address_delegation: Map::default(),
1082            generating_tree: MerkleTree::blank(DUST_GENERATION_TREE_DEPTH),
1083            generating_tree_first_free: 0,
1084            generating_set: HashSet::default(),
1085            night_indices: HashMap::default(),
1086            root_history: TimeFilterMap::new(),
1087        }
1088    }
1089}
1090
1091#[derive(Storable)]
1092#[derive_where(Clone, Debug, PartialEq, Eq, Default)]
1093#[storable(db = D)]
1094#[tag = "dust-state[v1]"]
1095#[must_use]
1096pub struct DustState<D: DB> {
1097    pub utxo: DustUtxoState<D>,
1098    pub generation: DustGenerationState<D>,
1099}
1100tag_enforcement_test!(DustState<InMemoryDB>);
1101
1102impl<D: DB> DustState<D> {
1103    pub(crate) fn apply_spend<P: ProofKind<D>>(
1104        &self,
1105        spend: &DustSpend<P, D>,
1106        time: Timestamp,
1107        context: &TransactionContext<D>,
1108        _params: &DustParameters,
1109        mut event_push: impl FnMut(Box<dyn FnOnce() -> EventDetails<D>>),
1110    ) -> Result<Self, TransactionInvalid<D>> {
1111        let mut state = self.clone();
1112        if state.utxo.nullifiers.member(&spend.old_nullifier) {
1113            warn!(?spend.old_nullifier, "dust double spend");
1114            return Err(TransactionInvalid::DustDoubleSpend(spend.old_nullifier));
1115        }
1116        state.utxo.nullifiers = state.utxo.nullifiers.insert(spend.old_nullifier);
1117        state.utxo.commitments = state
1118            .utxo
1119            .commitments
1120            .try_update_hash(
1121                self.utxo.commitments_first_free,
1122                spend.new_commitment.into(),
1123                (),
1124            )
1125            .map_err(TransactionInvalid::MerkleTreeError)?;
1126        state.utxo.commitments_first_free += 1;
1127        let commitment = spend.new_commitment;
1128        let commitment_index = state.utxo.commitments_first_free - 1;
1129        let nullifier = spend.old_nullifier;
1130        let v_fee = spend.v_fee;
1131        let block_time = context.block_context.tblock;
1132        event_push(Box::new(move || EventDetails::DustSpendProcessed {
1133            commitment,
1134            commitment_index,
1135            nullifier,
1136            v_fee,
1137            declared_time: time,
1138            block_time,
1139        }));
1140        Ok(state)
1141    }
1142
1143    #[allow(clippy::too_many_arguments)]
1144    pub(crate) fn apply_registration<S: SignatureKind<D>>(
1145        &self,
1146        utxo: &UtxoState<D>,
1147        mut fees_remaining: u128,
1148        parent_intent: &ErasedIntent<D>,
1149        registration: &DustRegistration<S, D>,
1150        dust_params: &DustParameters,
1151        context: &TransactionContext<D>,
1152        mut event_push: impl FnMut(Box<dyn FnOnce() -> EventDetails<D>>),
1153    ) -> Result<(Self, u128), TransactionInvalid<D>> {
1154        let night_address = UserAddress::from(registration.night_key.clone());
1155        let mut state = self.clone();
1156        match registration.dust_address.as_ref() {
1157            None => {
1158                if !state
1159                    .generation
1160                    .address_delegation
1161                    .contains_key(&night_address)
1162                {
1163                    warn!(?night_address, "non-registered deregistration attempt");
1164                    return Err(TransactionInvalid::DustDeregistrationNotRegistered(
1165                        night_address,
1166                    ));
1167                }
1168                state.generation.address_delegation =
1169                    state.generation.address_delegation.remove(&night_address);
1170            }
1171            Some(dust_address) => {
1172                state.generation.address_delegation = state
1173                    .generation
1174                    .address_delegation
1175                    .insert(night_address, **dust_address);
1176            }
1177        }
1178        let owned_outputs = parent_intent
1179            .guaranteed_unshielded_offer
1180            .iter()
1181            .flat_map(|o| o.outputs.iter_deref().enumerate())
1182            .filter(|(_, o)| o.owner == night_address && o.type_ == NIGHT)
1183            .collect::<Vec<_>>();
1184        let dust_in = self.generationless_fee_availability(
1185            utxo,
1186            parent_intent,
1187            &registration.night_key,
1188            dust_params,
1189        );
1190        let fee_paid = u128::min(
1191            fees_remaining,
1192            u128::min(registration.allow_fee_payment, dust_in),
1193        );
1194        fees_remaining -= fee_paid; // subtraction safe due to `min` above
1195        let dust_out = dust_in - fee_paid;
1196        if let Some(dust_addr) = registration.dust_address.as_ref() {
1197            let output_sum = owned_outputs
1198                .iter()
1199                .map(|(_, o)| o.value)
1200                .fold(0, u128::saturating_add);
1201            for (output_no, output) in owned_outputs.into_iter() {
1202                // NOTE: The ratio calculation could overflow even u128. As a
1203                // result, we quantize it.
1204                const DISTRIBUTION_RESOLUTION: u128 = 10_000;
1205                // NOTE: This arithmetic *should* be safe because of the NIGHT / DUST caps, and the
1206                // resolution, but we use saturating arithmetic anyway just in case.
1207                // NOTE: The corner case of output_sum = 0 can occur, because we currently don't
1208                // explicitly reject zero-value outputs. In this case, we *used to* panic here,
1209                // which the node would unwind by catching the panic, and rejecting the
1210                // transaction.
1211                // Instead, we now mark the transaction invalid. As this also results in
1212                // transaction rejection, this is a *backwards-compatible* fix.
1213                let ratio = output
1214                    .value
1215                    .saturating_mul(DISTRIBUTION_RESOLUTION)
1216                    .checked_div(output_sum)
1217                    .ok_or(TransactionInvalid::DivideByZero)?;
1218                let initial_value = ratio.saturating_mul(dust_out) / DISTRIBUTION_RESOLUTION;
1219                state = state.fresh_dust_output(
1220                    initial_nonce(output_no as u32, parent_intent.intent_hash(0)),
1221                    initial_value,
1222                    output.value,
1223                    **dust_addr,
1224                    context.block_context.tblock,
1225                    context.block_context.tblock,
1226                    &mut event_push,
1227                )?;
1228            }
1229        }
1230        Ok((state, fees_remaining))
1231    }
1232
1233    #[allow(clippy::too_many_arguments)]
1234    pub(crate) fn fresh_dust_output(
1235        &self,
1236        initial_nonce: InitialNonce,
1237        initial_value: u128,
1238        night_value: u128,
1239        dust_addr: DustPublicKey,
1240        tnow: Timestamp,
1241        tblock: Timestamp,
1242        mut event_push: impl FnMut(Box<dyn FnOnce() -> EventDetails<D>>),
1243    ) -> Result<Self, DustStateError> {
1244        let mut state = self.clone();
1245        let dust_pre_projection = DustPreProjection {
1246            initial_value,
1247            owner: dust_addr,
1248            nonce: dust_first_nonce(&initial_nonce, &dust_addr),
1249            ctime: tnow,
1250        };
1251        let dust_commitment = dust_pre_projection.commitment();
1252        state.utxo.commitments = state
1253            .utxo
1254            .commitments
1255            .try_update_hash(
1256                state.utxo.commitments_first_free,
1257                dust_commitment.into(),
1258                (),
1259            )
1260            .map_err(DustStateError::MerkleTreeError)?;
1261        state.utxo.commitments_first_free += 1;
1262        let gen_info = DustGenerationInfo {
1263            value: night_value,
1264            owner: dust_addr,
1265            nonce: initial_nonce,
1266            dtime: Timestamp::MAX,
1267        };
1268        if self.generation.night_indices.contains_key(&initial_nonce) {
1269            warn!(?initial_nonce, "already present initial_nonce info");
1270            return Err(DustStateError::InitialNonceAlreadyPresent(initial_nonce));
1271        }
1272        state.generation.generating_tree = state
1273            .generation
1274            .generating_tree
1275            .try_update_hash(
1276                state.generation.generating_tree_first_free,
1277                gen_info.merkle_hash(),
1278                gen_info,
1279            )
1280            .map_err(DustStateError::MerkleTreeError)?;
1281        state.generation.night_indices = state
1282            .generation
1283            .night_indices
1284            .insert(initial_nonce, self.generation.generating_tree_first_free);
1285        state.generation.generating_tree_first_free += 1;
1286
1287        let nonce = dust_pre_projection.nonce;
1288        let commitment_index = state.utxo.commitments_first_free - 1;
1289        let generation_index = state.generation.generating_tree_first_free - 1;
1290        event_push(Box::new(move || EventDetails::DustInitialUtxo {
1291            output: QualifiedDustOutput {
1292                initial_value,
1293                owner: dust_addr,
1294                nonce,
1295                seq: 0,
1296                ctime: tnow,
1297                backing_night: initial_nonce,
1298                mt_index: commitment_index,
1299            },
1300            generation: gen_info,
1301            generation_index,
1302            block_time: tblock,
1303        }));
1304
1305        Ok(state)
1306    }
1307
1308    pub(crate) fn generationless_fee_availability(
1309        &self,
1310        utxo_state: &UtxoState<D>,
1311        parent_intent: &ErasedIntent<D>,
1312        night_key: &SignatureVerifyingKey,
1313        params: &DustParameters,
1314    ) -> u128 {
1315        let generationless_inputs = parent_intent
1316            .guaranteed_unshielded_offer
1317            .iter()
1318            .flat_map(|o| o.inputs.iter_deref())
1319            .filter(|i| &i.owner == night_key && i.type_ == NIGHT)
1320            .filter(|i| {
1321                !self
1322                    .generation
1323                    .night_indices
1324                    .contains_key(&i.initial_nonce())
1325            });
1326        let Some(tend) = parent_intent.dust_actions.as_ref().map(|da| da.ctime) else {
1327            error!("reached generationless_fee_availability without dust actions");
1328            return 0;
1329        };
1330        generationless_inputs
1331            .map(|i| {
1332                let vfull = i.value.saturating_mul(params.night_dust_ratio as u128);
1333                let rate = i.value.saturating_mul(params.generation_decay_rate as u128);
1334                let Some(tstart) = utxo_state
1335                    .utxos
1336                    .get(&Utxo::from(i.clone()))
1337                    .map(|meta| meta.ctime)
1338                else {
1339                    warn!("couldn't get metadata of input utxo, it's likely invalid");
1340                    return 0;
1341                };
1342                let dt = (tend - tstart).as_seconds();
1343                let dt = if dt < 0 { 0 } else { dt as u128 };
1344                let value_unchecked = dt.saturating_mul(rate);
1345                u128::clamp(value_unchecked, 0, vfull)
1346            })
1347            .fold(0u128, |a, b| a.saturating_add(b))
1348    }
1349
1350    pub(crate) fn apply_offer<S: SignatureKind<D>>(
1351        &self,
1352        offer: &UnshieldedOffer<S, D>,
1353        parent: &ErasedIntent<D>,
1354        segment: u16,
1355        context: &TransactionContext<D>,
1356        mut event_push: impl FnMut(Box<dyn FnOnce() -> EventDetails<D>>),
1357    ) -> Result<Self, TransactionInvalid<D>> {
1358        let mut state = self.clone();
1359        for input in offer.inputs.iter_deref().filter(|i| i.type_ == NIGHT) {
1360            let Some(idx) = state.generation.night_indices.get(&input.initial_nonce()) else {
1361                continue;
1362            };
1363            let Some(mut gen_info) = state
1364                .generation
1365                .generating_tree
1366                .index(*idx)
1367                .map(|gen_info| *gen_info.1)
1368            else {
1369                error!(utxo = ?Utxo::from(input.clone()), ?idx, "invariant violated: `night_indices` reference not backed in `generating_tree`");
1370                debug_assert!(false);
1371                continue;
1372            };
1373            gen_info.dtime = context.block_context.tblock;
1374            state.generation.generating_tree = state
1375                .generation
1376                .generating_tree
1377                .try_update_hash(*idx, gen_info.merkle_hash(), gen_info)
1378                .map_err(TransactionInvalid::MerkleTreeError)?;
1379            let tree_snapshot = state.generation.generating_tree.clone();
1380            let idx = *idx;
1381            let block_time = context.block_context.tblock;
1382            event_push(Box::new(move || EventDetails::DustGenerationDtimeUpdate {
1383                // TODO: We maybe can do better than immediately rehashing here... But not much,
1384                // because anything in the insertion evidence in the event *will* need to be
1385                // computed here.
1386                update: tree_snapshot
1387                    .rehash()
1388                    .insertion_evidence(idx)
1389                    .expect("must be able to produce evidence for updated path"),
1390                block_time,
1391            }));
1392        }
1393        for (output_no, output) in offer
1394            .outputs
1395            .iter_deref()
1396            .enumerate()
1397            .filter(|(_, o)| o.type_ == NIGHT)
1398        {
1399            let Some(dust_addr) = state.generation.address_delegation.get(&output.owner) else {
1400                continue;
1401            };
1402            let handled_by_registration = segment == 0
1403                && parent
1404                    .dust_actions
1405                    .iter()
1406                    .flat_map(|actions| actions.registrations.iter_deref())
1407                    .any(|reg| output.owner == reg.night_key.clone().into());
1408            if !handled_by_registration {
1409                state = state.fresh_dust_output(
1410                    initial_nonce(output_no as u32, parent.intent_hash(segment)),
1411                    0,
1412                    output.value,
1413                    *dust_addr,
1414                    context.block_context.tblock,
1415                    context.block_context.tblock,
1416                    &mut event_push,
1417                )?;
1418            }
1419        }
1420        Ok(state)
1421    }
1422
1423    pub(crate) fn post_block_update(&self, tblock: Timestamp, global_ttl: Duration) -> Self {
1424        let mut res = self.clone();
1425        res.utxo.commitments = res.utxo.commitments.rehash();
1426        res.utxo.root_history = self
1427            .utxo
1428            .root_history
1429            .insert(
1430                tblock,
1431                res.utxo
1432                    .commitments
1433                    .root()
1434                    .expect("rehashed tree should have root"),
1435            )
1436            .filter(tblock - global_ttl);
1437        res.generation.generating_tree = res.generation.generating_tree.rehash();
1438        res.generation.root_history = self
1439            .generation
1440            .root_history
1441            .insert(
1442                tblock,
1443                res.generation
1444                    .generating_tree
1445                    .root()
1446                    .expect("rehashed tree should have root"),
1447            )
1448            .filter(tblock - global_ttl);
1449        res
1450    }
1451}
1452
1453pub const INITIAL_DUST_PARAMETERS: DustParameters = DustParameters {
1454    night_dust_ratio: 5 * (SPECKS_PER_DUST / STARS_PER_NIGHT) as u64, // 5 DUST per NIGHT
1455    generation_decay_rate: 8_267, // Works out to a generation time of approximately 1 week.
1456    dust_grace_period: Duration::from_hours(3),
1457};
1458
1459#[derive(Copy, Clone, Debug, Serializable, Storable)]
1460#[storable(base)]
1461#[tag = "dust-wallet-utxo-state[v1]"]
1462pub struct DustWalletUtxoState {
1463    pub utxo: QualifiedDustOutput,
1464    pub pending_until: Option<Timestamp>,
1465}
1466tag_enforcement_test!(DustWalletUtxoState);
1467
1468#[derive(Debug)]
1469pub enum DustSpendError {
1470    BackingNightNotFound(Box<QualifiedDustOutput>),
1471    NotEnoughDust { available: u128, required: u128 },
1472    DustUtxoNotTracked(Box<QualifiedDustOutput>),
1473    MerkleTreeNotRehashed(&'static str),
1474}
1475
1476impl Display for DustSpendError {
1477    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
1478        use DustSpendError as E;
1479        match self {
1480            E::BackingNightNotFound(utxo) => {
1481                write!(f, "backing Night of Dust UTXO not found (utxo: {utxo:?})")
1482            }
1483            E::NotEnoughDust {
1484                available,
1485                required,
1486            } => write!(
1487                f,
1488                "attempted to spend {required} Specks of Dust, but only {available} are available from this UTXO"
1489            ),
1490            E::DustUtxoNotTracked(utxo) => write!(
1491                f,
1492                "attempted to spend Dust UTXO that's not in the wallet state: {utxo:?}"
1493            ),
1494            E::MerkleTreeNotRehashed(tree) => write!(f, "{tree} Merkle tree is not fully rehashed"),
1495        }
1496    }
1497}
1498
1499impl Error for DustSpendError {}
1500
1501#[derive(Debug, Storable)]
1502#[derive_where(Clone)]
1503#[storable(db = D)]
1504#[tag = "dust-local-state[v1]"]
1505pub struct DustLocalState<D: DB> {
1506    pub generating_tree: MerkleTree<DustGenerationInfo, D>,
1507    pub generating_tree_first_free: u64,
1508    pub commitment_tree: MerkleTree<(), D>,
1509    pub commitment_tree_first_free: u64,
1510    night_indices: HashMap<InitialNonce, u64, D>,
1511    pub dust_utxos: HashMap<DustNullifier, DustWalletUtxoState, D>,
1512    pub sync_time: Timestamp,
1513    pub params: DustParameters,
1514}
1515tag_enforcement_test!(DustLocalState<InMemoryDB>);
1516
1517#[derive(Clone, Debug)]
1518pub struct DustStateChanges {
1519    pub received_utxos: Vec<QualifiedDustOutput>,
1520    pub spent_utxos: Vec<QualifiedDustOutput>,
1521    pub source: TransactionHash,
1522}
1523
1524impl DustStateChanges {
1525    pub fn can_merge(&self, other: &DustStateChanges) -> bool {
1526        self.source == other.source
1527    }
1528
1529    pub fn merge(&mut self, other: DustStateChanges) {
1530        self.received_utxos.extend(other.received_utxos);
1531        self.spent_utxos.extend(other.spent_utxos);
1532    }
1533}
1534
1535pub struct WithDustStateChanges<T> {
1536    pub changes: Vec<DustStateChanges>,
1537    pub result: T,
1538}
1539
1540impl<T> WithDustStateChanges<T> {
1541    pub fn new(result: T) -> WithDustStateChanges<T> {
1542        WithDustStateChanges {
1543            changes: Vec::new(),
1544            result,
1545        }
1546    }
1547}
1548
1549impl<T> WithDustStateChanges<T> {
1550    pub fn add_change(mut self, change: DustStateChanges) -> Self {
1551        if let Some(last_change) = self.changes.last_mut() {
1552            if last_change.can_merge(&change) {
1553                last_change.merge(change);
1554            } else {
1555                self.changes.push(change);
1556            }
1557        } else {
1558            self.changes.push(change);
1559        }
1560
1561        WithDustStateChanges {
1562            changes: self.changes,
1563            result: self.result,
1564        }
1565    }
1566
1567    pub fn maybe_add_change(self, maybe_change: Option<DustStateChanges>) -> Self {
1568        match maybe_change {
1569            Some(change) => self.add_change(change),
1570            None => self,
1571        }
1572    }
1573
1574    pub fn with_result(self, result: T) -> Self {
1575        WithDustStateChanges {
1576            changes: self.changes,
1577            result,
1578        }
1579    }
1580}
1581
1582impl<D: DB> DustLocalState<D> {
1583    pub fn new(params: DustParameters) -> Self {
1584        DustLocalState {
1585            generating_tree: MerkleTree::blank(DUST_GENERATION_TREE_DEPTH),
1586            generating_tree_first_free: 0,
1587            commitment_tree: MerkleTree::blank(DUST_COMMITMENT_TREE_DEPTH),
1588            commitment_tree_first_free: 0,
1589            night_indices: HashMap::new(),
1590            dust_utxos: HashMap::new(),
1591            sync_time: Timestamp::default(),
1592            params,
1593        }
1594    }
1595
1596    pub fn wallet_balance(&self, time: Timestamp) -> u128 {
1597        self.utxos()
1598            .filter_map(|utxo| {
1599                let gen_idx = *self.night_indices.get(&utxo.backing_night)?;
1600                let gen_info = self.generating_tree.index(gen_idx)?.1;
1601                Some(DustOutput::from(utxo).updated_value(gen_info, time, &self.params))
1602            })
1603            .sum()
1604    }
1605
1606    pub fn utxos(&self) -> impl Iterator<Item = QualifiedDustOutput> {
1607        self.dust_utxos.values().filter_map(|v| {
1608            if v.pending_until.is_none() {
1609                Some(v.utxo)
1610            } else {
1611                None
1612            }
1613        })
1614    }
1615
1616    pub fn find_utxo_by_nullifier(&self, nullifier: DustNullifier) -> Option<QualifiedDustOutput> {
1617        self.dust_utxos.get(&nullifier).and_then(|state| {
1618            if state.pending_until.is_none() {
1619                Some(state.utxo)
1620            } else {
1621                None
1622            }
1623        })
1624    }
1625
1626    pub fn add_utxo(
1627        &self,
1628        nullifier: &DustNullifier,
1629        utxo: &QualifiedDustOutput,
1630        pending_until: Option<Timestamp>,
1631    ) -> Result<Self, DustSpendError> {
1632        let mut state = self.clone();
1633        state.dust_utxos = state.dust_utxos.insert(
1634            *nullifier,
1635            DustWalletUtxoState {
1636                utxo: *utxo,
1637                pending_until,
1638            },
1639        );
1640        Ok(state)
1641    }
1642
1643    pub fn remove_utxo(&self, nullifier: &DustNullifier) -> Result<Self, DustSpendError> {
1644        let mut state = self.clone();
1645        state.dust_utxos = state.dust_utxos.remove(nullifier);
1646        Ok(state)
1647    }
1648
1649    pub fn generation_info(&self, qdo: &QualifiedDustOutput) -> Option<DustGenerationInfo> {
1650        Some(
1651            *self
1652                .generating_tree
1653                .index(*self.night_indices.get(&qdo.backing_night)?)?
1654                .1,
1655        )
1656    }
1657
1658    pub fn insert_generation_info(
1659        &self,
1660        generation_index: u64,
1661        gen_info: DustGenerationInfo,
1662        initial_nonce: Option<InitialNonce>,
1663    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1664        if generation_index != self.generating_tree_first_free {
1665            return Err(DustLocalStateError::NonLinearInsertion {
1666                expected_next: self.generating_tree_first_free,
1667                received: generation_index,
1668                tree_name: "dust generation",
1669            });
1670        }
1671
1672        let mut state = self.clone();
1673
1674        state.generating_tree = state
1675            .generating_tree
1676            .try_update_hash(generation_index, gen_info.merkle_hash(), gen_info)
1677            .map_err(DustLocalStateError::MerkleTreeError)?;
1678        state.generating_tree_first_free += 1;
1679        if let Some(initial_nonce) = initial_nonce {
1680            // TODO: shall we validate initial_nonce == gen_info.nonce ?
1681            state.night_indices = state.night_indices.insert(initial_nonce, generation_index);
1682        } else {
1683            state.generating_tree = state
1684                .generating_tree
1685                .collapse(generation_index, generation_index);
1686        }
1687        state.generating_tree = state.generating_tree.rehash();
1688        Ok(state)
1689    }
1690
1691    pub fn remove_generation_info(
1692        &self,
1693        generation_index: u64,
1694        gen_info: DustGenerationInfo,
1695    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1696        let actual_gen_info = self
1697            .generating_tree
1698            .index(generation_index)
1699            .ok_or(DustLocalStateError::GenerationIndexNotFound { generation_index })?
1700            .1;
1701
1702        if gen_info != *actual_gen_info {
1703            return Err(DustLocalStateError::WrongGenerationInfo { generation_index });
1704        }
1705
1706        let mut state = self.clone();
1707        state.generating_tree = state
1708            .generating_tree
1709            .collapse(generation_index, generation_index);
1710        state.generating_tree = state.generating_tree.rehash();
1711        Ok(state)
1712    }
1713
1714    pub fn collapse_generation_tree(
1715        &self,
1716        generation_index_start: u64,
1717        generation_index_end: u64,
1718    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1719        let mut state = self.clone();
1720        state.generating_tree = state
1721            .generating_tree
1722            .collapse(generation_index_start, generation_index_end);
1723        state.generating_tree = state.generating_tree.rehash();
1724        Ok(state)
1725    }
1726
1727    pub fn apply_generation_collapsed_update(
1728        &self,
1729        update: &MerkleTreeCollapsedUpdate,
1730    ) -> Result<Self, merkle_tree::InvalidUpdate> {
1731        Ok(Self {
1732            generating_tree: self
1733                .generating_tree
1734                .apply_collapsed_update(update)?
1735                .rehash(),
1736            generating_tree_first_free: u64::max(self.generating_tree_first_free, update.end + 1),
1737            ..self.clone()
1738        })
1739    }
1740
1741    pub fn insert_commitment(
1742        &self,
1743        commitment_index: u64,
1744        qdo: QualifiedDustOutput,
1745        own_qdo: bool,
1746    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1747        if commitment_index != self.commitment_tree_first_free {
1748            return Err(DustLocalStateError::NonLinearInsertion {
1749                expected_next: self.commitment_tree_first_free,
1750                received: commitment_index,
1751                tree_name: "commitment",
1752            });
1753        }
1754
1755        let mut state = self.clone();
1756
1757        state.commitment_tree = state
1758            .commitment_tree
1759            .try_update_hash(commitment_index, qdo.commitment().into(), ())
1760            .map_err(DustLocalStateError::MerkleTreeError)?;
1761        state.commitment_tree_first_free += 1;
1762        if !own_qdo {
1763            state.commitment_tree = state
1764                .commitment_tree
1765                .collapse(commitment_index, commitment_index);
1766        }
1767        state.commitment_tree = state.commitment_tree.rehash();
1768        Ok(state)
1769    }
1770
1771    pub fn remove_commitment(
1772        &self,
1773        commitment_index: u64,
1774    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1775        if self.commitment_tree.index(commitment_index).is_none() {
1776            return Err(DustLocalStateError::CommitmentIndexNotFound { commitment_index });
1777        }
1778
1779        let mut state = self.clone();
1780        state.commitment_tree = state
1781            .commitment_tree
1782            .collapse(commitment_index, commitment_index);
1783        state.commitment_tree = state.commitment_tree.rehash();
1784        Ok(state)
1785    }
1786
1787    pub fn collapse_commitment_tree(
1788        &self,
1789        commitment_index_start: u64,
1790        commitment_index_end: u64,
1791    ) -> Result<DustLocalState<D>, DustLocalStateError> {
1792        let mut state = self.clone();
1793        state.commitment_tree = state
1794            .commitment_tree
1795            .collapse(commitment_index_start, commitment_index_end);
1796        state.commitment_tree = state.commitment_tree.rehash();
1797        Ok(state)
1798    }
1799
1800    pub fn apply_commitment_collapsed_update(
1801        &self,
1802        update: &MerkleTreeCollapsedUpdate,
1803    ) -> Result<Self, merkle_tree::InvalidUpdate> {
1804        Ok(Self {
1805            commitment_tree: self
1806                .commitment_tree
1807                .apply_collapsed_update(update)?
1808                .rehash(),
1809            commitment_tree_first_free: u64::max(self.commitment_tree_first_free, update.end + 1),
1810            ..self.clone()
1811        })
1812    }
1813
1814    pub fn spend(
1815        &self,
1816        sk: &DustSecretKey,
1817        utxo: &QualifiedDustOutput,
1818        v_fee: u128,
1819        ctime: Timestamp,
1820    ) -> Result<(Self, DustSpend<ProofPreimageMarker, D>), DustSpendError> {
1821        let mut state = self.clone();
1822        let old_nullifier = utxo.nullifier(sk);
1823        let gen_idx = *self
1824            .night_indices
1825            .get(&utxo.backing_night)
1826            .ok_or(DustSpendError::BackingNightNotFound(Box::new(*utxo)))?;
1827        let gen_info = self
1828            .generating_tree
1829            .index(gen_idx)
1830            .ok_or(DustSpendError::BackingNightNotFound(Box::new(*utxo)))?
1831            .1;
1832        // TODO: Fixme: This is assuming that `generating_tree` *is* associated
1833        // with `ctime`. That seems backwards? We should figure out what `ctime`
1834        // these trees *are* associated with, then use that.
1835        let gen_path = self
1836            .generating_tree
1837            .path_for_leaf(gen_idx, gen_info.merkle_hash())
1838            .map_err(|_| DustSpendError::BackingNightNotFound(Box::new(*utxo)))?;
1839        let old_com = utxo.commitment();
1840        let old_nul = utxo.nullifier(sk);
1841        let com_path = self
1842            .commitment_tree
1843            .path_for_leaf(utxo.mt_index, HashOutput::from(old_com))
1844            .map_err(|_| DustSpendError::DustUtxoNotTracked(Box::new(*utxo)))?;
1845        let v_new = DustOutput::from(*utxo).updated_value(gen_info, ctime, &self.params);
1846        if v_fee > v_new {
1847            return Err(DustSpendError::NotEnoughDust {
1848                available: v_new,
1849                required: v_fee,
1850            });
1851        }
1852        let new_output = DustOutput {
1853            ctime,
1854            initial_value: v_new - v_fee,
1855            owner: utxo.owner,
1856            nonce: dust_nonce(&utxo.backing_night, utxo.seq + 1, sk),
1857            seq: utxo.seq + 1,
1858        };
1859        let new_commitment = new_output.commitment();
1860        let mut utxo_entry = *state
1861            .dust_utxos
1862            .get(&old_nullifier)
1863            .ok_or(DustSpendError::DustUtxoNotTracked(Box::new(*utxo)))?;
1864        utxo_entry.pending_until = Some(ctime + self.params.dust_grace_period);
1865        state.dust_utxos = state.dust_utxos.insert(old_nullifier, utxo_entry);
1866        let inputs = (
1867            DustOutput::from(*utxo),
1868            sk.clone(),
1869            *gen_info,
1870            com_path.clone(),
1871            gen_path.clone(),
1872            utxo.backing_night,
1873            utxo.seq,
1874        )
1875            .field_vec();
1876        let mut prog = Vec::new();
1877        // Check commitment merkle tree root
1878        prog.extend::<[Op<ResultModeGather, D>; 6]>(HistoricMerkleTree_check_root!(
1879            [Key::Value(DUST_IDX_COMMITMENT_TREE.into())],
1880            false,
1881            32,
1882            Fr,
1883            self.commitment_tree
1884                .root()
1885                .ok_or(DustSpendError::MerkleTreeNotRehashed("dust commitment"))?
1886        ));
1887        // Check generation merkle tree root
1888        prog.extend(HistoricMerkleTree_check_root!(
1889            [Key::Value(DUST_IDX_GENERATION_TREE.into())],
1890            false,
1891            32,
1892            Fr,
1893            self.generating_tree
1894                .root()
1895                .ok_or(DustSpendError::MerkleTreeNotRehashed(
1896                    "dust generation info"
1897                ))?
1898        ));
1899        // Read spend
1900        prog.extend(Cell_read!(
1901            [Key::Value(DUST_IDX_SPEND.into())],
1902            false,
1903            DustSpend
1904        ));
1905        // Read ctime
1906        prog.extend(Cell_read!([Key::Value(DUST_IDX_CTIME.into())], false, u64));
1907        // Read dust parameters
1908        prog.extend(Cell_read!(
1909            [Key::Value(DUST_IDX_PARAMETERS.into())],
1910            false,
1911            DustParameters
1912        ));
1913        // Insert old nullifier
1914        prog.extend(Set_insert!(
1915            [Key::Value(DUST_IDX_NULLIFIERS.into())],
1916            false,
1917            Fr,
1918            old_nul.0
1919        ));
1920        // Read ctime
1921        prog.extend(Cell_read!([Key::Value(DUST_IDX_CTIME.into())], false, u64));
1922        // Insert new commitment
1923        prog.extend(HistoricMerkleTree_insert_hash!(
1924            [Key::Value(DUST_IDX_COMMITMENT_TREE.into())],
1925            false,
1926            32,
1927            Fr,
1928            HashOutput::from(new_commitment)
1929        ));
1930        let mut public_transcript_inputs = vec![];
1931        let erased_spend = DustSpend::<(), D> {
1932            v_fee,
1933            old_nullifier,
1934            new_commitment,
1935            proof: (),
1936        };
1937        for op in with_outputs(
1938            prog.into_iter(),
1939            [
1940                true.into(),                 // commitment root check
1941                true.into(),                 // nullifier root check
1942                erased_spend.clone().into(), // dust spend read
1943                ctime.into(),                // ctime read
1944                self.params.into(),          // parameter read
1945                ctime.into(),                // ctime read
1946            ]
1947            .into_iter(),
1948        ) {
1949            op.field_repr(&mut public_transcript_inputs);
1950        }
1951        let public_transcript_outputs =
1952            (true, true, erased_spend, ctime, self.params, ctime).field_vec();
1953        let proof = ProofPreimage {
1954            inputs,
1955            public_transcript_inputs,
1956            public_transcript_outputs,
1957            binding_input: Default::default(),
1958            communications_commitment: None,
1959            private_transcript: vec![(v_new - v_fee).into()],
1960            key_location: KeyLocation(std::borrow::Cow::Borrowed("midnight/dust/spend")),
1961        };
1962        Ok((
1963            state,
1964            DustSpend {
1965                v_fee,
1966                old_nullifier,
1967                new_commitment,
1968                proof,
1969            },
1970        ))
1971    }
1972
1973    pub fn process_ttls(&self, time: Timestamp) -> Self {
1974        let mut state = self.clone();
1975        // Rebuild `night_indices` from the UTXOs that survive this pass, so it
1976        // stays bounded to nights still backing a live UTXO. `night_indices` is
1977        // only ever consulted via a held UTXO's `backing_night`, so entries for
1978        // dropped UTXOs are unreachable and safe to prune here.
1979        let mut night_indices = HashMap::new();
1980        state.dust_utxos = state
1981            .dust_utxos
1982            .iter()
1983            .filter_map(|utxo| {
1984                let nul = *utxo.0;
1985                let mut utxo = *utxo.1;
1986                let gen_idx = *self.night_indices.get(&utxo.utxo.backing_night)?;
1987                let gen_info = self.generating_tree.index(gen_idx)?.1;
1988                let v_new = DustOutput::from(utxo.utxo).updated_value(gen_info, time, &self.params);
1989                if utxo.pending_until.map(|ptime| ptime <= time) == Some(true) {
1990                    utxo.pending_until = None;
1991                }
1992                if v_new == 0 && time > utxo.utxo.ctime {
1993                    None
1994                } else {
1995                    night_indices = night_indices.insert(utxo.utxo.backing_night, gen_idx);
1996                    Some((nul, utxo))
1997                }
1998            })
1999            .collect();
2000        state.night_indices = night_indices;
2001        state
2002    }
2003
2004    pub fn replay_events<'a>(
2005        &self,
2006        sk: &DustSecretKey,
2007        events: impl IntoIterator<Item = &'a Event<D>>,
2008    ) -> Result<Self, EventReplayError> {
2009        self.replay_events_with_changes(sk, events)
2010            .map(|w| w.result)
2011    }
2012
2013    pub fn replay_events_with_changes<'a>(
2014        &self,
2015        sk: &DustSecretKey,
2016        events: impl IntoIterator<Item = &'a Event<D>>,
2017    ) -> Result<WithDustStateChanges<Self>, EventReplayError> {
2018        let pk = DustPublicKey::from(sk.clone());
2019        let (mut res, gen_collapses) = events.into_iter().try_fold(
2020            (WithDustStateChanges::new((*self).clone()), Vec::new()),
2021            |(mut acc, mut gen_collapses), event| {
2022                let maybe_change = match &event.content {
2023                    EventDetails::DustInitialUtxo {
2024                        output,
2025                        generation,
2026                        generation_index,
2027                        block_time,
2028                    } => {
2029                        if *generation_index != acc.result.generating_tree_first_free {
2030                            return Err(EventReplayError::NonLinearInsertion {
2031                                expected_next: acc.result.generating_tree_first_free,
2032                                received: *generation_index,
2033                                tree_name: "dust generation",
2034                            });
2035                        }
2036                        acc.result.generating_tree = acc
2037                            .result
2038                            .generating_tree
2039                            .try_update_hash(
2040                                *generation_index,
2041                                generation.merkle_hash(),
2042                                *generation,
2043                            )
2044                            .map_err(EventReplayError::MerkleTreeError)?;
2045                        acc.result.generating_tree_first_free += 1;
2046                        if output.mt_index != acc.result.commitment_tree_first_free {
2047                            return Err(EventReplayError::NonLinearInsertion {
2048                                expected_next: acc.result.commitment_tree_first_free,
2049                                received: output.mt_index,
2050                                tree_name: "dust commitment",
2051                            });
2052                        }
2053                        acc.result.commitment_tree = acc
2054                            .result
2055                            .commitment_tree
2056                            .try_update_hash(output.mt_index, output.commitment().into(), ())
2057                            .map_err(EventReplayError::MerkleTreeError)?;
2058                        acc.result.commitment_tree_first_free += 1;
2059                        let maybe_change = if pk == output.owner {
2060                            acc.result.night_indices = acc
2061                                .result
2062                                .night_indices
2063                                .insert(output.backing_night, *generation_index);
2064                            acc.result.dust_utxos = acc.result.dust_utxos.insert(
2065                                output.nullifier(sk),
2066                                DustWalletUtxoState {
2067                                    utxo: *output,
2068                                    pending_until: None,
2069                                },
2070                            );
2071                            Some(DustStateChanges {
2072                                received_utxos: vec![*output],
2073                                spent_utxos: vec![],
2074                                source: event.source.transaction_hash,
2075                            })
2076                        } else {
2077                            // Carry out generation collapses *after* applying all the events,
2078                            // because otherwise we might not have information around to process
2079                            // partial dtime updates due to these only being rehashed on block
2080                            // boundaries.
2081                            gen_collapses.push(*generation_index);
2082                            acc.result.commitment_tree = acc
2083                                .result
2084                                .commitment_tree
2085                                .collapse(output.mt_index, output.mt_index);
2086                            None
2087                        };
2088                        if *block_time < acc.result.sync_time {
2089                            return Err(EventReplayError::EventForPastTime {
2090                                synced: acc.result.sync_time,
2091                                event: *block_time,
2092                            });
2093                        }
2094                        acc.result.sync_time = *block_time;
2095                        maybe_change
2096                    }
2097                    EventDetails::ParamChange(params) => {
2098                        acc.result.params = params.dust;
2099                        None
2100                    }
2101                    EventDetails::DustSpendProcessed {
2102                        commitment,
2103                        commitment_index,
2104                        nullifier,
2105                        v_fee,
2106                        declared_time,
2107                        block_time,
2108                    } => {
2109                        if *commitment_index != acc.result.commitment_tree_first_free {
2110                            return Err(EventReplayError::NonLinearInsertion {
2111                                expected_next: acc.result.commitment_tree_first_free,
2112                                received: *commitment_index,
2113                                tree_name: "dust commitment",
2114                            });
2115                        }
2116                        acc.result.commitment_tree = acc
2117                            .result
2118                            .commitment_tree
2119                            .try_update_hash(*commitment_index, (*commitment).into(), ())
2120                            .map_err(EventReplayError::MerkleTreeError)?;
2121                        acc.result.commitment_tree_first_free += 1;
2122                        let maybe_change = if let Some(utxo) = acc.result.dust_utxos.get(nullifier)
2123                        {
2124                            if let Some(gen_info) = acc
2125                                .result
2126                                .night_indices
2127                                .get(&utxo.utxo.backing_night)
2128                                .and_then(|gen_idx| acc.result.generating_tree.index(*gen_idx))
2129                                .map(|(_, gen_info)| *gen_info)
2130                            {
2131                                let v_pre_spend = DustOutput::from(utxo.utxo).updated_value(
2132                                    &gen_info,
2133                                    *declared_time,
2134                                    &acc.result.params,
2135                                );
2136                                let v_now = v_pre_spend.saturating_sub(*v_fee);
2137                                let spent_utxo = utxo.utxo;
2138                                acc.result.dust_utxos = acc.result.dust_utxos.remove(nullifier);
2139                                let qdo_new = QualifiedDustOutput {
2140                                    backing_night: spent_utxo.backing_night,
2141                                    ctime: *declared_time,
2142                                    initial_value: v_now,
2143                                    seq: spent_utxo.seq + 1,
2144                                    nonce: dust_nonce(
2145                                        &spent_utxo.backing_night,
2146                                        spent_utxo.seq + 1,
2147                                        sk,
2148                                    ),
2149                                    owner: spent_utxo.owner,
2150                                    mt_index: *commitment_index,
2151                                };
2152                                acc.result.dust_utxos = acc.result.dust_utxos.insert(
2153                                    qdo_new.nullifier(sk),
2154                                    DustWalletUtxoState {
2155                                        utxo: qdo_new,
2156                                        pending_until: None,
2157                                    },
2158                                );
2159                                Some(DustStateChanges {
2160                                    received_utxos: vec![qdo_new],
2161                                    spent_utxos: vec![spent_utxo],
2162                                    source: event.source.transaction_hash,
2163                                })
2164                            } else {
2165                                error!("Unable to find backing NIGHT");
2166                                None
2167                            }
2168                        } else {
2169                            acc.result.commitment_tree = acc
2170                                .result
2171                                .commitment_tree
2172                                .collapse(*commitment_index, *commitment_index);
2173                            None
2174                        };
2175                        if *block_time < acc.result.sync_time {
2176                            return Err(EventReplayError::EventForPastTime {
2177                                synced: acc.result.sync_time,
2178                                event: *block_time,
2179                            });
2180                        }
2181                        acc.result.sync_time = *block_time;
2182                        maybe_change
2183                    }
2184                    EventDetails::DustGenerationDtimeUpdate { update, block_time } => {
2185                        debug_assert!(update.path.iter().all(|entry| entry.hash.is_some()));
2186                        acc.result.generating_tree = acc
2187                            .result
2188                            .generating_tree
2189                            .update_from_evidence(update.clone())?;
2190                        if *block_time < acc.result.sync_time {
2191                            return Err(EventReplayError::EventForPastTime {
2192                                synced: acc.result.sync_time,
2193                                event: *block_time,
2194                            });
2195                        }
2196                        acc.result.sync_time = *block_time;
2197                        None
2198                    }
2199                    _ => None,
2200                };
2201                Ok((acc.maybe_add_change(maybe_change), gen_collapses))
2202            },
2203        )?;
2204        for collapse in gen_collapses {
2205            res.result.generating_tree = res.result.generating_tree.collapse(collapse, collapse);
2206        }
2207        res.result.commitment_tree = res.result.commitment_tree.rehash();
2208        res.result.generating_tree = res.result.generating_tree.rehash();
2209        Ok(res)
2210    }
2211}
2212
2213#[allow(clippy::too_many_arguments)]
2214pub fn successor_utxo(
2215    utxo: &QualifiedDustOutput,
2216    now: &Timestamp,
2217    subtract_fee: u128,
2218    new_commitment_index: u64,
2219    gen_info: &DustGenerationInfo,
2220    sk: &DustSecretKey,
2221    params: &DustParameters,
2222) -> QualifiedDustOutput {
2223    let v_pre_spend = DustOutput::from(*utxo).updated_value(gen_info, *now, params);
2224    let v_now = v_pre_spend.saturating_sub(subtract_fee);
2225    QualifiedDustOutput {
2226        backing_night: utxo.backing_night,
2227        ctime: *now,
2228        initial_value: v_now,
2229        seq: utxo.seq.saturating_add(1),
2230        nonce: dust_nonce(&utxo.backing_night, utxo.seq.saturating_add(1), sk),
2231        owner: utxo.owner,
2232        mt_index: new_commitment_index,
2233    }
2234}
2235
2236macro_rules! exptfile {
2237    ($name:literal, $desc:literal) => {
2238        (
2239            concat!("dust/", midnight_ledger_static::version!(), "/", $name),
2240            base_crypto::data_provider::hexhash(
2241                &include_bytes!(concat!("../static/dust/", $name, ".sha256"))
2242                    .split_at(64)
2243                    .0,
2244            ),
2245            $desc,
2246        )
2247    };
2248}
2249
2250/// Files provided by Midnight's data provider for Dust.
2251pub const DUST_EXPECTED_FILES: &[(&str, [u8; 32], &str)] = &[
2252    exptfile!("spend.prover", "zero-knowledge proving key for Dust spends"),
2253    exptfile!(
2254        "spend.verifier",
2255        "zero-knowledge verifying key for Dust spends"
2256    ),
2257    exptfile!("spend.bzkir", "ZKIR source for Dust spends"),
2258];
2259
2260pub const DUST_SPEND_PROOF_SIZE: usize = 2_912;
2261pub const DUST_SPEND_PIS: usize = 138;
2262
2263#[cfg(test)]
2264mod tests {
2265    use super::{DustSecretKey, Seed};
2266    use hex::FromHex;
2267    use serde::de::{Error, Unexpected};
2268    use serde::{Deserialize, Deserializer};
2269    use std::fs;
2270
2271    #[cfg(feature = "proving")]
2272    #[tokio::test]
2273    async fn test_proof_size() {
2274        use base_crypto::rng::SplittableRng;
2275        use rand::{Rng, SeedableRng, rngs::StdRng};
2276        use storage::db::InMemoryDB;
2277        use transient_crypto::commitment::{Pedersen, PedersenRandomness};
2278        use zkir_v2::LocalProvingProvider;
2279
2280        use crate::{
2281            dust::DUST_SPEND_PROOF_SIZE,
2282            test_utilities::{TestState, test_resolver},
2283        };
2284
2285        let mut rng = StdRng::seed_from_u64(0x42);
2286        let mut state = TestState::<InMemoryDB>::new(&mut rng);
2287        state.give_fee_token(&mut rng, 1).await;
2288        let utxo = state.dust.utxos().next().unwrap();
2289        let dust_spend = state
2290            .dust
2291            .spend(&state.dust_key, &utxo, 42, state.time)
2292            .unwrap()
2293            .1;
2294        let resolver = test_resolver("");
2295        let prover = LocalProvingProvider {
2296            rng: rng.split(),
2297            params: &resolver,
2298            resolver: &resolver,
2299        };
2300        let binding = Pedersen::from(rng.r#gen::<PedersenRandomness>());
2301        let proven_dust_spend = dust_spend.prove(prover, 0, binding).await.unwrap();
2302        assert_eq!(proven_dust_spend.proof.0.len(), DUST_SPEND_PROOF_SIZE);
2303    }
2304
2305    struct WrappedSeed(pub Seed);
2306    impl<'de> Deserialize<'de> for WrappedSeed {
2307        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2308        where
2309            D: Deserializer<'de>,
2310        {
2311            let s = <String as Deserialize>::deserialize(deserializer)?;
2312            let as_arr: [u8; 32] = <[u8; 32]>::from_hex(s.clone())
2313                .map_err(|_err| Error::invalid_value(Unexpected::Str(&s), &"hex string"))?;
2314            Ok(WrappedSeed(as_arr))
2315        }
2316    }
2317
2318    struct HexArr64([u8; 64]);
2319    impl<'de> Deserialize<'de> for HexArr64 {
2320        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2321        where
2322            D: Deserializer<'de>,
2323        {
2324            let s = <String as Deserialize>::deserialize(deserializer)?;
2325            let arr: [u8; 64] = <[u8; 64]>::from_hex(s.clone()).map_err(|_err| {
2326                println!("{}", _err);
2327                Error::invalid_value(Unexpected::Str(&s), &"hex string")
2328            })?;
2329            Ok(HexArr64(arr))
2330        }
2331    }
2332
2333    struct HexArr32([u8; 32]);
2334    impl<'de> Deserialize<'de> for HexArr32 {
2335        fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
2336        where
2337            D: Deserializer<'de>,
2338        {
2339            let s = <String as Deserialize>::deserialize(deserializer)?;
2340            let arr: [u8; 32] = <[u8; 32]>::from_hex(s.clone()).map_err(|_err| {
2341                println!("{}", _err);
2342                Error::invalid_value(Unexpected::Str(&s), &"hex string")
2343            })?;
2344            Ok(HexArr32(arr))
2345        }
2346    }
2347
2348    #[allow(non_snake_case, dead_code)]
2349    #[derive(Deserialize)]
2350    struct EncryptionVectorEntry {
2351        secretKeyRepr: HexArr32,
2352        secretKeyDecimal: String,
2353        secretKeyIntermediateBytes: HexArr64,
2354    }
2355
2356    #[allow(non_snake_case)]
2357    #[derive(Deserialize)]
2358    struct VectorEntry {
2359        seed: WrappedSeed,
2360        dust: EncryptionVectorEntry,
2361    }
2362
2363    struct TestVectors(Vec<VectorEntry>);
2364    impl TestVectors {
2365        fn load() -> TestVectors {
2366            let raw = fs::read("key-derivation-test-vectors.json").unwrap();
2367            let parsed: Vec<VectorEntry> = serde_json::from_slice(raw.as_slice()).unwrap();
2368            TestVectors(parsed)
2369        }
2370    }
2371
2372    #[test]
2373    fn encryption_key_derivation_matches_test_vectors() {
2374        use transient_crypto::curve::Fr;
2375        let test_vectors = TestVectors::load();
2376
2377        for entry in test_vectors.0 {
2378            let dsk_computed = DustSecretKey::derive_secret_key(&entry.seed.0);
2379            let dsk_reference =
2380                DustSecretKey(Fr::from_le_bytes(&entry.dust.secretKeyRepr.0).unwrap());
2381            let intermediate_computed =
2382                DustSecretKey::sample_bytes(&entry.seed.0, 64, b"midnight:dsk");
2383            let dsk_from_intermediate = DustSecretKey(Fr::from_uniform_bytes(
2384                &entry.dust.secretKeyIntermediateBytes.0,
2385            ));
2386
2387            println!("Encryption Keys:");
2388            println!("  seed:                  {:?}", entry.seed.0);
2389            println!(
2390                "  intermediate bytes:    {:?}",
2391                entry.dust.secretKeyIntermediateBytes.0
2392            );
2393            println!(
2394                "  intermediate computed: {:?}",
2395                intermediate_computed.as_slice()
2396            );
2397            println!("  computed:              {:?}", dsk_computed.repr());
2398            println!("  reference:             {:?}", dsk_reference.repr());
2399            println!("  reference raw:         {:?}", entry.dust.secretKeyRepr.0);
2400            println!(
2401                "  from intermediate:     {:?}",
2402                dsk_from_intermediate.repr()
2403            );
2404
2405            assert_eq!(
2406                intermediate_computed.as_slice(),
2407                entry.dust.secretKeyIntermediateBytes.0.as_slice(),
2408                "Intermediate bytes do not match"
2409            );
2410            assert_eq!(
2411                dsk_computed.repr(),
2412                dsk_from_intermediate.repr(),
2413                "Key computed from seed does not match key computed from intermediate bytes"
2414            );
2415            assert_eq!(
2416                dsk_computed.repr(),
2417                dsk_reference.repr(),
2418                "Key computed from seed does not match reference"
2419            );
2420            assert_eq!(
2421                dsk_reference.repr(),
2422                dsk_from_intermediate.repr(),
2423                "Key computed from intermediate bytes does not match reference"
2424            );
2425        }
2426    }
2427}