moonproof-wallet 0.2.1

Native Rust wallet for the Midnight blockchain — HD derivation, coin balancing, Zswap/unshielded/dust transacting
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
//! Indexer-driven wallet sync.
//!
//! `sync_wallet_resumable` is the core entry point: takes an optional
//! prior `FacadeState` (from a persisted snapshot) and folds in the
//! new ticks since the snapshot's applied indexes. `sync_wallet_fresh`
//! is the same path with no resume — replays from genesis.
//!
//! Persistence lives outside the session module — hosts that want a
//! disk-backed snapshot wrap these primitives with their own load /
//! save layer (see CLI's `wallet/chain.rs` for the redb-backed
//! example).

use std::time::Duration as StdDuration;

use anyhow::{anyhow, Context, Result};
use futures::StreamExt;
use moonproof_indexer_client::{
    subscribe_dust_ledger_events, subscribe_shielded_transactions,
    subscribe_unshielded_transactions, HttpIndexerClient, PublicDataProvider, ShieldedTxRaw,
    UnshieldedTxRaw,
};
use moonproof_ledger::base_crypto::time::Timestamp;
use moonproof_ledger::ledger::structure::LedgerParameters;

use crate::abstractions::ProtocolVersion;
use crate::facade::{
    fetch_chain_parameters, fold_dust_events, fold_shielded_ticks, fold_unshielded_ticks,
    FacadeState,
};
use crate::runtime::ExponentialBackoff;
use crate::shielded::ShieldedState;
use crate::testing::Wallet;
use crate::{DustState, UnshieldedState};

use super::connect::WalletSession;

/// Hard ceiling for poll-based wait helpers (`wait_for_*_balance`).
/// Acts as a safety belt for non-poll callers so a totally
/// unresponsive indexer can't pin a process.
///
/// 60 s suits local-dev. Public networks override via
/// [`resolve_indexer_sync_timeout`] (env var
/// `MOONPROOF_INDEXER_SYNC_TIMEOUT_SECS`).
pub const INDEXER_SYNC_TIMEOUT: StdDuration = StdDuration::from_secs(60);

/// Resolve the indexer sync ceiling for `network`. Honors the env var
/// `MOONPROOF_INDEXER_SYNC_TIMEOUT_SECS` first; otherwise picks a
/// network-aware default:
///
/// - local-dev (Undeployed): 60 s — fast, shallow history.
/// - preview / preprod: 300 s — public networks with months of
///   history and slower indexer aggregation under load.
/// - mainnet: 600 s — same logic, with extra headroom because the
///   stakes don't allow a balance check to silently truncate.
#[must_use]
pub fn resolve_indexer_sync_timeout(network: &super::network::NetworkConfig) -> StdDuration {
    use crate::abstractions::NetworkId;
    if let Ok(s) = std::env::var("MOONPROOF_INDEXER_SYNC_TIMEOUT_SECS") {
        if let Ok(secs) = s.parse::<u64>() {
            return StdDuration::from_secs(secs);
        }
    }
    match &network.network_id {
        NetworkId::Undeployed => StdDuration::from_secs(60),
        NetworkId::MainNet => StdDuration::from_secs(600),
        _ => StdDuration::from_secs(300),
    }
}

/// Per-message idle timeout for drain loops. Idle alone is NOT proof
/// of being caught up — a loaded indexer can stall mid-backfill for
/// longer than this. Idle only ends a drain once the indexer-reported
/// watermark confirms every relevant item has been applied; otherwise
/// the drain re-opens the subscription and lets the indexer's first
/// progress tick adjudicate (bounded by [`MAX_IDLE_VERIFIES`]).
const DRAIN_IDLE_TIMEOUT: StdDuration = StdDuration::from_secs(2);

/// Maximum *consecutive* failed reconnect attempts before a drain
/// gives up and surfaces an error to the caller. The counter resets
/// on every successfully received tick, so a long backfill tolerates
/// any number of sporadic drops — only a sustained outage (5 failures
/// in a row, ~worst case `5 * MAX_BACKOFF`) aborts, without losing
/// progress already folded into the facade.
const MAX_RECONNECTS: u32 = 5;

/// How many times an idle drain re-opens its subscription to verify
/// the watermark before accepting the state it has. Only reached when
/// the indexer never reports a progress watermark at all.
const MAX_IDLE_VERIFIES: u32 = 2;

/// Ceiling on opening a subscription (TCP + WS handshake + first
/// server ack). Without it a half-dead indexer socket can pin a
/// drain — and any host sync loop above it — forever.
const SUBSCRIBE_OPEN_TIMEOUT: StdDuration = StdDuration::from_secs(15);

/// `subscribe.await` with [`SUBSCRIBE_OPEN_TIMEOUT`], flattening the
/// timeout into the subscription's own error type so reconnect arms
/// treat both identically.
async fn open_with_timeout<T, E, F>(fut: F, what: &str) -> std::result::Result<T, String>
where
    F: std::future::Future<Output = std::result::Result<T, E>>,
    E: std::fmt::Display,
{
    match moonproof_utils::rt::timeout(SUBSCRIBE_OPEN_TIMEOUT, fut).await {
        Ok(Ok(v)) => Ok(v),
        Ok(Err(e)) => Err(format!("{what}: {e}")),
        Err(_) => Err(format!(
            "{what}: open timed out after {}s",
            SUBSCRIBE_OPEN_TIMEOUT.as_secs()
        )),
    }
}

/// Identity of the chain *instance* behind `session` — the hash of
/// block 1, queried from the indexer, falling back to the node's
/// genesis hash when block 1 doesn't exist yet (brand-new chain).
///
/// The genesis hash alone is NOT instance-unique: two runs of the
/// same local-dev chain spec share a deterministic genesis, but
/// block 1 carries a timestamp so its hash differs per run. Snapshot
/// stores compare this value to refuse resuming state captured
/// against a chain that was since reset.
pub async fn chain_instance_id(session: &WalletSession) -> Option<String> {
    use moonproof_indexer_client::BlockOffset;
    use moonproof_node_client::NodeClient;
    if let Ok(client) = HttpIndexerClient::new(&session.network.indexer_http) {
        if let Ok(Ok(Some(block))) = moonproof_utils::rt::timeout(
            SUBSCRIBE_OPEN_TIMEOUT,
            client.block(Some(BlockOffset::Height(1))),
        )
        .await
        {
            return Some(block.hash);
        }
    }
    session.node.genesis_hash_hex()
}

/// Sync without touching any disk store — every call replays from
/// genesis. Convenience wrapper around [`sync_wallet_resumable`] with
/// `prior = None`. Returns the [`FacadeState`] with chain-tip
/// timestamp set; callers needing the timestamp call
/// [`FacadeState::chain_tip_ts`].
pub async fn sync_wallet_fresh(session: &WalletSession) -> Result<FacadeState> {
    sync_wallet_resumable(session, None).await
}

/// Resume sync from `prior` (taken from a persisted [`crate::WalletSnapshot`])
/// and only fold ticks past `prior`'s applied indexes. When `prior`
/// is `None`, replays from genesis.
pub async fn sync_wallet_resumable(
    session: &WalletSession,
    prior: Option<FacadeState>,
) -> Result<FacadeState> {
    let (start, drained) = Box::pin(drain_wallet_sync(session, prior)).await?;
    let synced = drained.fold_into(start, &session.wallet)?;
    Box::pin(settle_at_rooted_block(session, synced)).await
}

/// How long [`settle_at_rooted_block`] keeps syncing toward a block
/// whose dust roots the local trees hold, and how often it rereads the
/// tip. The indexer's tip moves on as the drain runs, and dust events
/// in that gap leave the trees one block behind; a further drain
/// closes it within moments unless the wallet cannot keep up.
const ROOTED_BLOCK_TIMEOUT: StdDuration = StdDuration::from_secs(120);
const ROOTED_BLOCK_POLL: StdDuration = StdDuration::from_secs(1);

/// Stamp `facade` with the newest block whose dust-tree roots its local
/// trees hold, draining further while they hold the roots of none.
///
/// Every spend the facade builds is dated at its chain-tip time, and
/// the node verifies a dust spend's proof against the roots it recorded
/// at that time. Dated at a block whose roots the local trees do not
/// hold, the proof is built over different trees and the node rejects
/// it as an invalid dust spend proof. A tip without reported roots is
/// taken as it is, as midnight-wallet does.
async fn settle_at_rooted_block(
    session: &WalletSession,
    mut facade: FacadeState,
) -> Result<FacadeState> {
    use crate::dust::DustTreeRoots;

    let deadline = moonproof_utils::rt::Instant::now() + ROOTED_BLOCK_TIMEOUT;
    loop {
        let tip = fetch_chain_parameters(&session.network.indexer_http)
            .await
            .map_err(|e| anyhow!("fetch chain parameters: {e}"))?;
        let local = DustTreeRoots::of(&facade.dust);
        match &tip.dust_roots {
            Some(reported) if *reported != local => {
                if moonproof_utils::rt::Instant::now() >= deadline {
                    return Err(anyhow!(
                        "the wallet's dust trees hold roots (commitment {}, generation {}) that no \
                         block reports: block {} reports commitment {}, generation {} after {}s of \
                         syncing",
                        local.commitment,
                        local.generation,
                        tip.block_height,
                        reported.commitment,
                        reported.generation,
                        ROOTED_BLOCK_TIMEOUT.as_secs()
                    ));
                }
                tracing::debug!(
                    block = tip.block_height,
                    "sync: dust trees not at the tip's roots; draining again"
                );
                moonproof_utils::rt::sleep(ROOTED_BLOCK_POLL).await;
                let (start, drained) = Box::pin(drain_wallet_sync(session, Some(facade))).await?;
                facade = drained.fold_into(start, &session.wallet)?;
            }
            _ => {
                return Ok(facade
                    .with_chain_tip_ts(Timestamp::from_secs(tip.chain_time_secs))
                    .with_ledger_parameters(tip.ledger_parameters)
                    .with_protocol_version(tip.protocol_version));
            }
        }
    }
}

/// Drain every tick past `prior`'s applied indexes (from genesis when
/// `prior` is `None`) without folding any. Returns the facade the drain
/// started from, which stands in for the host's state when it holds
/// none, together with the ticks.
pub async fn drain_wallet_sync(
    session: &WalletSession,
    prior: Option<FacadeState>,
) -> Result<(FacadeState, DrainedTicks)> {
    tracing::info!(
        indexer = %moonproof_indexer_client::redact_project_id(&session.network.indexer_http),
        resume = prior.is_some(),
        "sync: fetch_chain_parameters"
    );
    let params = fetch_chain_parameters(&session.network.indexer_http)
        .await
        .map_err(|e| anyhow!("fetch chain parameters: {e}"))?;
    let block_ts = Timestamp::from_secs(params.chain_time_secs);
    tracing::info!(
        chain_time_secs = params.chain_time_secs,
        "sync: chain_parameters_ok"
    );

    let dust_sk = session.wallet.dust_secret_key();
    let zswap_keys = session.wallet.zswap_secret_keys();

    let (facade, unshielded_start, shielded_start, dust_start) = if let Some(p) = prior {
        let unshielded_start = indexer_cursor(p.unshielded_progress().applied_index)?;
        // A shielded applied index is a transaction's zswap end
        // index, already the next free one, and the indexer streams
        // the transactions starting at or after the index it is
        // given: one past it skips a transaction that starts there.
        let shielded_start = indexer_cursor(p.shielded.progress().applied_index)?;
        let dust_start = indexer_cursor(p.dust.progress().applied_index)?;
        (p, unshielded_start + 1, shielded_start, dust_start + 1)
    } else {
        let facade = FacadeState::new(
            ShieldedState::init_empty(&zswap_keys, session.network.network_id.clone()),
            UnshieldedState::empty(),
            DustState::init_empty(
                params.ledger_parameters.dust,
                &dust_sk,
                session.network.network_id.clone(),
            ),
            session.network.network_id.clone(),
        );
        let dust_start = fresh_dust_start(&session.network.indexer_http).await;
        (facade, 0, 0, dust_start)
    };

    tracing::info!(unshielded_start, "sync: drain_unshielded");
    let unshielded = Box::pin(drain_unshielded_from(
        &session.network.indexer_http,
        &session.wallet.bech32_address,
        unshielded_start,
    ))
    .await?;
    tracing::info!(ticks = unshielded.len(), "sync: unshielded_drained");

    tracing::info!(shielded_start, "sync: drain_shielded");
    let shielded = Box::pin(drain_shielded_from(
        &session.network.indexer_http,
        &session.wallet,
        shielded_start,
    ))
    .await
    .with_context(|| "draining shielded transaction subscription")?;
    tracing::info!(ticks = shielded.len(), "sync: shielded_drained");

    tracing::info!(dust_start, "sync: drain_dust");
    let (dust, dust_max_id) = Box::pin(drain_dust_from(
        &session.network.indexer_http,
        dust_start,
        dust_start,
    ))
    .await?;
    tracing::info!(blobs = dust.len(), dust_max_id, "sync: dust_drained");

    let drained = DrainedTicks {
        started_at: AppliedIndexes::of(&facade),
        unshielded,
        shielded,
        dust,
        dust_max_id,
        chain_time: block_ts,
        ledger_parameters: params.ledger_parameters,
        protocol_version: params.protocol_version,
    };
    Ok((facade, drained))
}

/// An applied index as the indexer's signed cursor.
fn indexer_cursor(applied_index: u64) -> Result<i64> {
    i64::try_from(applied_index).map_err(|_| {
        anyhow!("applied index {applied_index} exceeds the indexer's i64 cursor range")
    })
}

/// Reconnect budget shared by the drain loops: at most
/// [`MAX_RECONNECTS`] consecutive attempts, reset on every received tick.
struct Reconnects {
    backoff: ExponentialBackoff,
    attempts: u32,
}

impl Reconnects {
    fn new() -> Self {
        Self {
            backoff: ExponentialBackoff::new().with_jitter(),
            attempts: 0,
        }
    }

    fn reset(&mut self) {
        self.backoff.reset();
        self.attempts = 0;
    }

    /// The delay before the next attempt, or `None` once the budget is spent.
    fn next_wait(&mut self) -> Option<StdDuration> {
        if self.attempts >= MAX_RECONNECTS {
            return None;
        }
        self.attempts += 1;
        Some(self.backoff.next_delay())
    }
}

/// Ticks [`drain_wallet_sync`] collected, to be folded into whatever
/// state the host holds once the drain ends rather than the one it
/// started from, so a spend booked or released meanwhile survives.
pub struct DrainedTicks {
    started_at: AppliedIndexes,
    unshielded: Vec<UnshieldedTxRaw>,
    shielded: Vec<ShieldedTxRaw>,
    dust: Vec<(i64, String)>,
    dust_max_id: i64,
    chain_time: Timestamp,
    ledger_parameters: LedgerParameters,
    protocol_version: ProtocolVersion,
}

#[derive(Debug, Clone, Copy)]
struct AppliedIndexes {
    unshielded: u64,
    shielded: u64,
    dust: u64,
}

impl AppliedIndexes {
    fn of(facade: &FacadeState) -> Self {
        Self {
            unshielded: facade.unshielded_progress().applied_index,
            shielded: facade.shielded.progress().applied_index,
            dust: facade.dust.progress().applied_index,
        }
    }
}

/// Whether a tick at `index` was applied by a fold since the drain
/// started at `started`, now that the state is at `now`. An index the
/// state never moved past is not, so an unmoved state takes every tick.
fn applied_since(index: Option<i64>, started: u64, now: u64) -> bool {
    now > started && index.is_some_and(|index| u64::try_from(index).is_ok_and(|index| index <= now))
}

impl DrainedTicks {
    /// Chain time at the tip the drain read, which dust folds against.
    #[must_use]
    pub fn chain_time(&self) -> Timestamp {
        self.chain_time
    }

    /// Fold the drained ticks into `facade`, skipping those a fold since
    /// the drain started already applied to it. Replaying one would
    /// put a UTXO created there back among the available ones even
    /// when `facade` books it, and break the shielded and dust trees.
    pub fn fold_into(self, facade: FacadeState, wallet: &Wallet) -> Result<FacadeState> {
        let now = AppliedIndexes::of(&facade);
        let started = self.started_at;

        let unshielded = self
            .unshielded
            .into_iter()
            .filter(|t| !applied_since(t.transaction_id, started.unshielded, now.unshielded));
        let facade = fold_unshielded_ticks(facade, wallet.owner_bytes(), unshielded)
            .map_err(|e| anyhow!("fold unshielded ticks: {e}"))?;

        let shielded = self
            .shielded
            .into_iter()
            .filter(|t| !applied_since(t.zswap_end_index, started.shielded, now.shielded));
        let facade = fold_shielded_ticks(facade, &wallet.zswap_secret_keys(), shielded)
            .map_err(|e| anyhow!("fold shielded ticks: {e}"))?;

        let dust_blobs: Vec<String> = self
            .dust
            .into_iter()
            .filter(|(id, _)| !applied_since(Some(*id), started.dust, now.dust))
            .map(|(_, raw)| raw)
            .collect();
        let (facade, _) = fold_dust_events(
            facade,
            &wallet.dust_secret_key(),
            &dust_blobs,
            self.chain_time,
        )
        .map_err(|e| anyhow!("fold dust events: {e}"))?;

        // Advance dust applied_index past everything we just folded so
        // the next reactive-sync iteration resumes from `max_id + 1`
        // rather than re-draining the same events. The dust state
        // doesn't track ids itself — the indexer-side raw id is the
        // authoritative cursor. The drain only returns once the stream
        // confirmed `max_id` is the chain's highest dust event, so the
        // relevant watermark equals the applied cursor — without it,
        // `is_strictly_complete` reports a permanent phantom gap.
        let facade = if let Ok(dust_max_id) = u64::try_from(self.dust_max_id) {
            let applied = dust_max_id.max(now.dust);
            let dust_progress_update = crate::dust::SyncProgressUpdate::new()
                .with_applied_index(applied)
                .with_highest_relevant_wallet_index(applied)
                .with_is_connected(true);
            let next_dust = facade.dust.clone().update_progress(dust_progress_update);
            facade.with_dust(next_dust)
        } else {
            facade
        };

        tracing::info!("sync: done");
        Ok(facade
            .with_chain_tip_ts(self.chain_time)
            .with_ledger_parameters(self.ledger_parameters)
            .with_protocol_version(self.protocol_version))
    }
}

/// Where a fresh dust sync starts. The ledger 8 -> 9 fork reset dust
/// state and re-emitted it as ledger-9 events, so a ledger-9 build
/// starts at the first of those and skips history it cannot read; on a
/// chain born on ledger 9 that is the beginning. Best-effort, as in
/// midnight-wallet: when the search fails, read from the beginning.
async fn fresh_dust_start(indexer_http: &str) -> i64 {
    if moonproof_ledger::ERA != moonproof_ledger::LedgerEra::V9 {
        return 0;
    }
    match moonproof_indexer_client::subscription::find_dust_timeline_start(
        indexer_http,
        moonproof_ledger::LEDGER_9_PROTOCOL_VERSION,
    )
    .await
    {
        Ok(Some(id)) => {
            tracing::info!(id, "sync: dust starts at the ledger-9 fork");
            id
        }
        Ok(None) => 0,
        Err(e) => {
            tracing::warn!(error = %e, "sync: could not locate the ledger-9 dust start; reading from the beginning");
            0
        }
    }
}

/// Shielded drain progress across subscription (re)opens.
struct ShieldedDrain {
    start_index: i64,
    // Reconnect-aware watermark — `end_index` of the highest tick we
    // have already folded. An end index is exclusive, so on WebSocket
    // drop we re-open the subscription at `cursor` itself.
    cursor: i64,
    // Highest relevant end-index the indexer has reported for this
    // wallet. `-1` until the first tick carries one; `cursor >=
    // highest_relevant_seen` is the only condition that counts as a
    // confirmed catch-up (index-to-index, same unit on both sides).
    highest_relevant_seen: i64,
    out: Vec<ShieldedTxRaw>,
    debug: bool,
}

impl ShieldedDrain {
    fn new(start_index: i64) -> Self {
        Self {
            start_index,
            cursor: start_index.max(0).saturating_sub(1),
            highest_relevant_seen: -1,
            out: Vec::new(),
            debug: std::env::var("MOONPROOF_SHIELDED_SYNC_DEBUG")
                .ok()
                .as_deref()
                == Some("1"),
        }
    }

    fn caught_up(&self) -> bool {
        self.highest_relevant_seen >= 0 && self.cursor >= self.highest_relevant_seen
    }

    /// Records one received tick; `Ok(true)` ends the drain.
    fn apply(&mut self, tick: ShieldedTxRaw) -> Result<bool> {
        if self.debug {
            eprintln!(
                "  shielded-tick progress={} tx_hash={:?} end_index={:?} highest_zswap={:?} highest_relevant={:?} highest_checked={:?} events={}",
                tick.is_progress(),
                tick.transaction_hash,
                tick.zswap_end_index,
                tick.highest_zswap_end_index,
                tick.highest_relevant_zswap_end_index,
                tick.highest_checked_zswap_end_index,
                tick.zswap_ledger_events.len(),
            );
        }
        let is_progress = tick.is_progress();
        // Resuming past the chain's own end-index means the
        // chain lost zswap events the snapshot already
        // applied — reset chain or wrong chain instance.
        if is_progress && self.start_index > 1 {
            if let Some(h) = tick.highest_zswap_end_index {
                if h < self.start_index - 1 {
                    return Err(crate::error::WalletError::StaleSnapshot {
                        scope: "zswap end",
                        snapshot_applied: self.start_index - 1,
                        chain_highest: h,
                    }
                    .into());
                }
            }
        }
        if let Some(h) = tick.highest_relevant_zswap_end_index {
            self.highest_relevant_seen = self.highest_relevant_seen.max(h);
        }
        // Skip ticks the facade has already applied —
        // a reconnect can redeliver the last tick, and
        // re-folding a merkle update is a hard error.
        let already_applied = tick
            .zswap_end_index
            .is_some_and(|end_idx| end_idx <= self.cursor);
        if let Some(end_idx) = tick.zswap_end_index {
            self.cursor = self.cursor.max(end_idx);
        }
        if !already_applied {
            self.out.push(tick);
        }
        if self.caught_up() {
            return Ok(true);
        }
        // Progress tick reporting no relevant txs at all.
        Ok(is_progress && self.highest_relevant_seen <= 0)
    }
}

/// Open a `shieldedTransactions` subscription against the indexer and
/// drain ticks until the highest-relevant index is exhausted or the
/// sync timeout fires.
async fn drain_shielded_from(
    indexer_http: &str,
    wallet: &Wallet,
    start_index: i64,
) -> Result<Vec<ShieldedTxRaw>> {
    let viewing_key = wallet
        .viewing_key_bech32m()
        .map_err(|e| anyhow!("encoding shielded viewing key: {e}"))?;
    let indexer =
        HttpIndexerClient::new(indexer_http).map_err(|e| anyhow!("indexer URL parse: {e}"))?;
    let mut drain = ShieldedDrain::new(start_index);
    let mut reconnects = Reconnects::new();
    let mut idle_verifies: u32 = 0;

    'outer: loop {
        let resume_idx = drain.cursor.max(start_index);
        // A fresh indexer session per (re)open: session IDs are
        // server-side state with eviction/TTL, so a reconnect must
        // never reuse one — the indexer answers stale IDs with
        // "unknown or expired session ID" indefinitely.
        let open = open_with_timeout(
            async {
                let session_id = indexer
                    .connect(&viewing_key, None)
                    .await
                    .map_err(|e| format!("indexer rejected viewing key: {e}"))?;
                subscribe_shielded_transactions(indexer_http, &session_id, Some(resume_idx))
                    .await
                    .map_err(|e| e.to_string())
            },
            "shielded subscription",
        );
        let mut sub = match Box::pin(open).await {
            Ok(s) => s,
            Err(e) => {
                let Some(wait) = reconnects.next_wait() else {
                    return Err(anyhow!(
                        "shielded subscription failed to (re)open after {MAX_RECONNECTS} \
                         attempts: {e}"
                    ));
                };
                tracing::warn!(
                    attempt = reconnects.attempts,
                    delay_ms = wait.as_millis(),
                    "shielded subscription open failed: {e}; retrying after backoff"
                );
                moonproof_utils::rt::sleep(wait).await;
                continue;
            }
        };

        loop {
            match moonproof_utils::rt::timeout(DRAIN_IDLE_TIMEOUT, sub.next()).await {
                Err(_) => {
                    if drain.caught_up() {
                        break 'outer;
                    }
                    if idle_verifies >= MAX_IDLE_VERIFIES {
                        tracing::warn!(
                            cursor = drain.cursor,
                            highest_relevant_seen = drain.highest_relevant_seen,
                            "shielded drain idle without watermark confirmation; \
                             accepting current state"
                        );
                        break 'outer;
                    }
                    idle_verifies += 1;
                    continue 'outer;
                }
                Ok(Some(Ok(tick))) => {
                    reconnects.reset();
                    if drain.apply(tick)? {
                        break 'outer;
                    }
                }
                // Server-side close (`None`) is a drop, not a
                // catch-up signal — an indexer restart mid-backfill
                // must not truncate sync silently.
                Ok(dropped) => {
                    let reason = match dropped {
                        None => "server closed the stream".to_owned(),
                        Some(Err(e)) => format!("{e:?}"),
                        Some(Ok(_)) => unreachable!("handled above"),
                    };
                    let cursor = drain.cursor;
                    let Some(wait) = reconnects.next_wait() else {
                        return Err(anyhow!(
                            "shielded subscription dropped after {MAX_RECONNECTS} reconnect \
                             attempts at cursor={cursor}: {reason}"
                        ));
                    };
                    tracing::warn!(
                        attempt = reconnects.attempts,
                        delay_ms = wait.as_millis(),
                        "shielded subscription dropped at cursor={cursor}: {reason}; \
                         reconnecting"
                    );
                    moonproof_utils::rt::sleep(wait).await;
                    continue 'outer;
                }
            }
        }
    }
    Ok(drain.out)
}

/// Unshielded drain progress across subscription (re)opens.
struct UnshieldedDrain {
    start_id: i64,
    // Resume-aware watermark: when caller passes `start_id = N + 1`
    // (snapshot already applied everything through `N`), the indexer
    // emits a progress tick with `highest_transaction_id = N` and no
    // real ticks. Initialising to `start_id - 1` lets the
    // `last_applied >= highest_seen` break fire on that first
    // progress tick instead of looping until the global deadline.
    last_applied: i64,
    // `-1` until the indexer reports a watermark; idle only counts as
    // caught up once a progress tick has confirmed it.
    highest_seen: i64,
    collected: Vec<UnshieldedTxRaw>,
}

impl UnshieldedDrain {
    fn new(start_id: i64) -> Self {
        Self {
            start_id,
            last_applied: (start_id - 1).max(0),
            highest_seen: -1,
            collected: Vec::new(),
        }
    }

    fn caught_up(&self) -> bool {
        self.highest_seen >= 0 && self.last_applied >= self.highest_seen
    }

    fn resume_start(&self) -> Option<i64> {
        if self.last_applied > 0 {
            Some(self.last_applied + 1)
        } else if self.start_id > 0 {
            Some(self.start_id)
        } else {
            None
        }
    }

    /// Records one received tick; `Ok(true)` ends the drain.
    fn apply(&mut self, tick: UnshieldedTxRaw) -> Result<bool> {
        if tick.is_progress() {
            let reported = tick.highest_transaction_id.unwrap_or(0);
            // Resuming past the chain's own watermark means
            // the chain lost events the snapshot already
            // applied — reset chain or wrong chain instance.
            if self.start_id > 1 && reported < self.start_id - 1 {
                return Err(crate::error::WalletError::StaleSnapshot {
                    scope: "unshielded transaction",
                    snapshot_applied: self.start_id - 1,
                    chain_highest: reported,
                }
                .into());
            }
            self.highest_seen = self.highest_seen.max(reported);
            self.collected.push(tick);
            return Ok(self.last_applied >= self.highest_seen);
        }
        // Skip redelivered ticks the facade already
        // applied — a stale failure tick would otherwise
        // resurrect spent UTXOs.
        if tick
            .transaction_id
            .is_some_and(|id| id <= self.last_applied && self.start_id > 0)
        {
            return Ok(false);
        }
        if let Some(id) = tick.transaction_id {
            self.last_applied = self.last_applied.max(id);
        }
        self.collected.push(tick);
        Ok(self.caught_up())
    }
}

/// Drain the indexer's `unshieldedTransactions(viewing-address)`
/// subscription until the recipient's progress watermark catches up
/// or the global timeout fires. `start_id = 0` replays from genesis;
/// positive values resume from the snapshot's last applied index.
async fn drain_unshielded_from(
    indexer_url: &str,
    bech32_address: &str,
    start_id: i64,
) -> Result<Vec<UnshieldedTxRaw>> {
    let mut drain = UnshieldedDrain::new(start_id);
    let mut reconnects = Reconnects::new();
    let mut idle_verifies: u32 = 0;

    'outer: loop {
        let open = open_with_timeout(
            subscribe_unshielded_transactions(indexer_url, bech32_address, drain.resume_start()),
            "unshielded subscription",
        );
        let mut stream = match Box::pin(open).await {
            Ok(s) => s,
            Err(e) => {
                let Some(wait) = reconnects.next_wait() else {
                    return Err(anyhow!(
                        "unshielded subscription failed to (re)open after \
                         {MAX_RECONNECTS} attempts: {e}"
                    ));
                };
                tracing::warn!(
                    attempt = reconnects.attempts,
                    delay_ms = wait.as_millis(),
                    "unshielded subscription open failed: {e}; retrying after backoff"
                );
                moonproof_utils::rt::sleep(wait).await;
                continue;
            }
        };

        loop {
            match moonproof_utils::rt::timeout(DRAIN_IDLE_TIMEOUT, stream.next()).await {
                Err(_) => {
                    if drain.caught_up() {
                        break 'outer;
                    }
                    if idle_verifies >= MAX_IDLE_VERIFIES {
                        tracing::warn!(
                            last_applied = drain.last_applied,
                            highest_seen = drain.highest_seen,
                            "unshielded drain idle without watermark confirmation; \
                             accepting current state"
                        );
                        break 'outer;
                    }
                    idle_verifies += 1;
                    continue 'outer;
                }
                Ok(Some(Ok(tick))) => {
                    reconnects.reset();
                    if drain.apply(tick)? {
                        break 'outer;
                    }
                }
                // Server-side close is a drop, not a catch-up signal.
                Ok(dropped) => {
                    let reason = match dropped {
                        None => "server closed the stream".to_owned(),
                        Some(Err(e)) => format!("{e}"),
                        Some(Ok(_)) => unreachable!("handled above"),
                    };
                    let last_applied = drain.last_applied;
                    let Some(wait) = reconnects.next_wait() else {
                        return Err(anyhow!(
                            "unshielded subscription dropped after {MAX_RECONNECTS} \
                             reconnect attempts at last_applied={last_applied}: {reason}"
                        ));
                    };
                    tracing::warn!(
                        attempt = reconnects.attempts,
                        delay_ms = wait.as_millis(),
                        "unshielded subscription dropped at last_applied={last_applied}: \
                         {reason}; reconnecting"
                    );
                    moonproof_utils::rt::sleep(wait).await;
                    continue 'outer;
                }
            }
        }
    }
    Ok(drain.collected)
}

/// Drain the indexer's global `dustLedgerEvents` subscription. Walks
/// from `start_id` (or 0 for full replay) until `ev.max_id <= ev.id`
/// or the timeout fires. Returns `(blobs, max_id)` so the caller can
/// advance the dust sub-state's `applied_index` past every event we
/// just folded — without it, a poll-based reactive loop re-drains
/// the same events on its next iteration and the dust generation
/// tree rejects the duplicate inserts ("expected to insert index N,
/// received 0").
///
/// `max_id` is `-1` when the indexer returned no events (fresh chain
/// with no dust activity yet).
async fn drain_dust_from(
    indexer_url: &str,
    start_id: i64,
    skip_below: i64,
) -> Result<(Vec<(i64, String)>, i64)> {
    let mut out = Vec::new();
    let mut max_id: i64 = skip_below.saturating_sub(1);
    let mut reconnects = Reconnects::new();

    'outer: loop {
        let resume_start = if max_id >= 0 {
            Some(max_id + 1)
        } else if start_id > 0 {
            Some(start_id)
        } else {
            Some(0)
        };
        let open = open_with_timeout(
            subscribe_dust_ledger_events(indexer_url, resume_start),
            "dust subscription",
        );
        let mut stream = match Box::pin(open).await {
            Ok(s) => s,
            Err(e) => {
                let Some(wait) = reconnects.next_wait() else {
                    return Err(anyhow!(
                        "dust subscription failed to (re)open after {MAX_RECONNECTS} \
                         attempts: {e}"
                    ));
                };
                tracing::warn!(
                    attempt = reconnects.attempts,
                    delay_ms = wait.as_millis(),
                    "dust subscription open failed: {e}; retrying after backoff"
                );
                moonproof_utils::rt::sleep(wait).await;
                continue;
            }
        };

        loop {
            match moonproof_utils::rt::timeout(DRAIN_IDLE_TIMEOUT, stream.next()).await {
                // The dust stream has no progress watermark when zero
                // events exist past the cursor, so idle is the only
                // available catch-up signal here.
                Err(_) => break 'outer,
                // Server-side close is a drop, not a catch-up signal.
                Ok(None | Some(Err(_))) => {
                    let Some(wait) = reconnects.next_wait() else {
                        return Err(anyhow!(
                            "dust subscription dropped after {MAX_RECONNECTS} \
                             reconnect attempts at max_id={max_id}"
                        ));
                    };
                    tracing::warn!(
                        attempt = reconnects.attempts,
                        delay_ms = wait.as_millis(),
                        "dust subscription dropped at max_id={max_id}; reconnecting"
                    );
                    moonproof_utils::rt::sleep(wait).await;
                    continue 'outer;
                }
                Ok(Some(Ok(ev))) => {
                    reconnects.reset();
                    if ev.id > max_id {
                        out.push((ev.id, ev.raw.clone()));
                        max_id = ev.id;
                    }
                    if ev.max_id <= ev.id {
                        break 'outer;
                    }
                }
            }
        }
    }
    Ok((out, max_id))
}

#[cfg(test)]
mod tests {
    use moonproof_indexer_client::{BlockRef, UnshieldedUtxoRaw};
    use moonproof_ledger::base_crypto::time::Duration;
    use moonproof_ledger::ledger::dust::DustParameters;
    use moonproof_ledger::ledger::structure::INITIAL_PARAMETERS;

    use super::*;
    use crate::abstractions::NetworkId;
    use crate::unshielded::UtxoId;

    fn wallet() -> Wallet {
        Wallet::from_hex_seed(
            "0000000000000000000000000000000000000000000000000000000000000007",
            NetworkId::Undeployed,
        )
        .unwrap()
    }

    fn empty_facade(wallet: &Wallet) -> FacadeState {
        FacadeState::new(
            ShieldedState::init_empty(&wallet.zswap_secret_keys(), NetworkId::Undeployed),
            UnshieldedState::empty(),
            DustState::init_empty(
                DustParameters {
                    night_dust_ratio: 1_000,
                    generation_decay_rate: 1,
                    dust_grace_period: Duration::from_secs(60),
                },
                &wallet.dust_secret_key(),
                NetworkId::Undeployed,
            ),
            NetworkId::Undeployed,
        )
    }

    fn creating(id: i64, intent_byte: u8) -> UnshieldedTxRaw {
        UnshieldedTxRaw {
            kind: "UnshieldedTransaction".to_owned(),
            status: Some("SUCCESS".to_owned()),
            transaction_id: Some(id),
            transaction_hash: Some(format!("{id:064x}")),
            block: Some(BlockRef {
                hash: "00".to_owned(),
                height: id,
            }),
            block_time_secs: Some(1_700_000_000),
            created_utxos: vec![UnshieldedUtxoRaw {
                owner: String::new(),
                token_type: "00".repeat(32),
                value: "1000".to_owned(),
                intent_hash: hex::encode([intent_byte; 32]),
                output_index: 0,
                ctime: Some(1_700_000_000),
                initial_nonce: "cd".to_owned(),
                registered_for_dust_generation: false,
            }],
            spent_utxos: Vec::new(),
            highest_transaction_id: None,
        }
    }

    fn utxo(intent_byte: u8) -> UtxoId {
        UtxoId::new([intent_byte; 32], 0)
    }

    fn drained(started_from: &FacadeState, unshielded: Vec<UnshieldedTxRaw>) -> DrainedTicks {
        DrainedTicks {
            started_at: AppliedIndexes::of(started_from),
            unshielded,
            shielded: Vec::new(),
            dust: Vec::new(),
            dust_max_id: -1,
            chain_time: Timestamp::from_secs(1_700_000_100),
            ledger_parameters: INITIAL_PARAMETERS,
            protocol_version: ProtocolVersion(2_001_100),
        }
    }

    #[test]
    fn the_fold_carries_the_tip_protocol_version() {
        let wallet = wallet();
        let start = empty_facade(&wallet);
        let ticks = drained(&start, Vec::new());

        let folded = ticks.fold_into(start, &wallet).unwrap();

        assert_eq!(folded.protocol_version(), ProtocolVersion(2_001_100));
    }

    fn book(facade: FacadeState, id: UtxoId) -> FacadeState {
        let unshielded = facade.unshielded.clone().spend_by_id(id).unwrap();
        facade.with_unshielded(unshielded)
    }

    #[test]
    fn a_spend_booked_while_draining_survives_the_fold() {
        let wallet = wallet();
        let start = fold_unshielded_ticks(
            empty_facade(&wallet),
            wallet.owner_bytes(),
            [creating(1, 0xA1)],
        )
        .unwrap();
        let ticks = drained(&start, vec![creating(2, 0xB2)]);
        let booked = book(start, utxo(0xA1));

        let folded = ticks.fold_into(booked, &wallet).unwrap();

        assert!(folded.unshielded.has_pending(&utxo(0xA1)));
        assert!(!folded.unshielded.has_available(&utxo(0xA1)));
        assert!(folded.unshielded.has_available(&utxo(0xB2)));
        assert_eq!(folded.unshielded_progress().applied_index, 2);
        assert_eq!(folded.chain_tip_ts(), Timestamp::from_secs(1_700_000_100));
    }

    #[test]
    fn ticks_a_fold_applied_while_draining_are_not_replayed() {
        let wallet = wallet();
        let start = fold_unshielded_ticks(
            empty_facade(&wallet),
            wallet.owner_bytes(),
            [creating(1, 0xA1)],
        )
        .unwrap();
        let ticks = drained(&start, vec![creating(2, 0xB2), creating(3, 0xC3)]);
        let advanced =
            fold_unshielded_ticks(start, wallet.owner_bytes(), [creating(2, 0xB2)]).unwrap();
        let booked = book(advanced, utxo(0xB2));

        let folded = ticks.fold_into(booked, &wallet).unwrap();

        assert!(folded.unshielded.has_pending(&utxo(0xB2)));
        assert!(!folded.unshielded.has_available(&utxo(0xB2)));
        assert!(folded.unshielded.has_available(&utxo(0xC3)));
        assert_eq!(folded.unshielded_progress().applied_index, 3);
    }

    #[test]
    fn an_unmoved_state_takes_every_tick_including_the_first() {
        let wallet = wallet();
        let start = empty_facade(&wallet);
        let ticks = drained(&start, vec![creating(0, 0xA0), creating(1, 0xA1)]);

        let folded = ticks.fold_into(start, &wallet).unwrap();

        assert!(folded.unshielded.has_available(&utxo(0xA0)));
        assert!(folded.unshielded.has_available(&utxo(0xA1)));
    }
}