zingolib 7.0.0

Zingo backend library.
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
//! Serialization of [`MigrationState`] into the wallet file.
//!
//! The section carries its own version byte, independent of
//! `LightWallet::serialized_version`, so future layout changes here never
//! bump the wallet version again.

use std::io::{self, Error, ErrorKind, Read, Write};

use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use zcash_encoding::{Optional, Vector};
use zcash_primitives::transaction::TxId;
use zcash_protocol::consensus::BlockHeight;

use pepper_sync::wallet::OutputId;

use super::params::MigrationParams;
use super::parts::{BoundNote, BoundaryWitness, PartId, PartRecord, PartState, SigningStrategy};
use super::{ConsentBinding, MigrationMode, MigrationPhase, MigrationState};

/// Version of this section's layout, bumped independently of the wallet
/// version. Version 2 appends the [`MigrationMode`] byte after the parts.
/// Version 3 drops the params `expiry_delta` field: the canonical expiry is
/// the fixed ZIP 318 formula, not a parameter. Version 4 appends each part's
/// `anchor_bucket` after its `bucket_index`, the anchor having become a
/// bucket of its own rather than the transmission window's (ADR 0018).
const INNER_VERSION: u8 = 4;

/// Serializes the migration section.
pub fn write<W: Write>(mut writer: W, state: &MigrationState) -> io::Result<()> {
    writer.write_u8(INNER_VERSION)?;

    let params = &state.params;
    writer.write_u32::<LittleEndian>(params.version)?;
    Vector::write(&mut writer, &params.denominations, |w, denomination| {
        w.write_u64::<LittleEndian>(*denomination)
    })?;
    writer.write_u64::<LittleEndian>(params.denom_cap)?;
    writer.write_u64::<LittleEndian>(params.max_residual_value)?;
    writer.write_u64::<LittleEndian>(params.sweep_min)?;
    writer.write_u32::<LittleEndian>(params.bucket_modulus)?;
    writer.write_u32::<LittleEndian>(params.k_max)?;
    writer.write_u32::<LittleEndian>(params.target_sessions)?;
    writer.write_u64::<LittleEndian>(params.max_actions_per_split_tx as u64)?;
    writer.write_u64::<LittleEndian>(params.part_fee)?;

    writer.write_all(&state.consent.params_hash)?;
    writer.write_all(&state.consent.plan_hash)?;
    writer.write_u64::<LittleEndian>(state.consent.consented_at)?;

    writer.write_u8(match state.strategy {
        SigningStrategy::LazyAtBoundary => 0,
        SigningStrategy::PreSigned => 1,
    })?;
    writer.write_u32::<LittleEndian>(state.account.into())?;

    match &state.phase {
        MigrationPhase::Planned => writer.write_u8(0)?,
        MigrationPhase::NoteSplitting {
            round,
            pending_txids,
        } => {
            writer.write_u8(1)?;
            writer.write_u32::<LittleEndian>(*round)?;
            Vector::write(&mut writer, pending_txids, |w, txid| txid.write(w))?;
        }
        MigrationPhase::PartsScheduled => writer.write_u8(2)?,
        MigrationPhase::Complete { residual } => {
            writer.write_u8(3)?;
            writer.write_u64::<LittleEndian>(*residual)?;
        }
    }

    Vector::write(&mut writer, &state.parts, |w, part| write_part(w, part))?;

    writer.write_u8(match state.mode {
        MigrationMode::Scheduled => 0,
        MigrationMode::Immediate => 1,
    })
}

/// Deserializes the migration section.
pub fn read<R: Read>(mut reader: R) -> io::Result<MigrationState> {
    let inner_version = reader.read_u8()?;
    if inner_version > INNER_VERSION {
        return Err(Error::new(
            ErrorKind::InvalidData,
            format!("unknown migration section version {inner_version}"),
        ));
    }

    let version = reader.read_u32::<LittleEndian>()?;
    let denominations = Vector::read(&mut reader, |r| r.read_u64::<LittleEndian>())?;
    let denom_cap = reader.read_u64::<LittleEndian>()?;
    let max_residual_value = reader.read_u64::<LittleEndian>()?;
    let sweep_min = reader.read_u64::<LittleEndian>()?;
    let bucket_modulus = reader.read_u32::<LittleEndian>()?;
    // Every bucket computation divides or multiplies by the modulus, so a
    // zero from a corrupt file must fail typed here, not panic downstream.
    if bucket_modulus == 0 {
        return Err(Error::new(
            ErrorKind::InvalidData,
            "bucket_modulus must be nonzero",
        ));
    }
    let k_max = reader.read_u32::<LittleEndian>()?;
    let target_sessions = reader.read_u32::<LittleEndian>()?;
    let max_actions_per_split_tx =
        usize::try_from(reader.read_u64::<LittleEndian>()?).map_err(|_| {
            Error::new(
                ErrorKind::InvalidData,
                "max_actions_per_split_tx does not fit in this platform's usize",
            )
        })?;
    if inner_version <= 2 {
        // Discarded: superseded by the fixed ZIP 318 expiry formula.
        reader.read_u32::<LittleEndian>()?;
    }
    let part_fee = reader.read_u64::<LittleEndian>()?;
    let params = MigrationParams {
        version,
        denominations,
        denom_cap,
        max_residual_value,
        sweep_min,
        bucket_modulus,
        k_max,
        target_sessions,
        max_actions_per_split_tx,
        part_fee,
    };

    let mut params_hash = [0u8; 32];
    reader.read_exact(&mut params_hash)?;
    let mut plan_hash = [0u8; 32];
    reader.read_exact(&mut plan_hash)?;
    let consented_at = reader.read_u64::<LittleEndian>()?;
    let consent = ConsentBinding {
        params_hash,
        plan_hash,
        consented_at,
    };

    let strategy = match reader.read_u8()? {
        0 => SigningStrategy::LazyAtBoundary,
        1 => SigningStrategy::PreSigned,
        other => {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("invalid signing strategy {other}"),
            ));
        }
    };
    let account = zip32::AccountId::try_from(reader.read_u32::<LittleEndian>()?)
        .map_err(|e| Error::new(ErrorKind::InvalidData, format!("invalid account id: {e}")))?;

    let phase = match reader.read_u8()? {
        0 => MigrationPhase::Planned,
        1 => {
            let round = reader.read_u32::<LittleEndian>()?;
            let pending_txids = Vector::read(&mut reader, |r| TxId::read(r))?;
            MigrationPhase::NoteSplitting {
                round,
                pending_txids,
            }
        }
        2 => MigrationPhase::PartsScheduled,
        3 => MigrationPhase::Complete {
            residual: reader.read_u64::<LittleEndian>()?,
        },
        other => {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("invalid migration phase {other}"),
            ));
        }
    };

    let parts = Vector::read(&mut reader, |r| read_part(r, inner_version))?;

    // Version 1 predates the mode marker. Scheduled is the conservative
    // reading: it makes the immediate path refuse to collapse the state
    // rather than assume the user consented to an immediate migration.
    let mode = if inner_version >= 2 {
        match reader.read_u8()? {
            0 => MigrationMode::Scheduled,
            1 => MigrationMode::Immediate,
            other => {
                return Err(Error::new(
                    ErrorKind::InvalidData,
                    format!("invalid migration mode {other}"),
                ));
            }
        }
    } else {
        MigrationMode::Scheduled
    };

    Ok(MigrationState {
        params,
        consent,
        strategy,
        mode,
        account,
        phase,
        parts,
    })
}

fn write_part<W: Write>(mut writer: W, part: &PartRecord) -> io::Result<()> {
    writer.write_u32::<LittleEndian>(part.id.0)?;
    writer.write_u64::<LittleEndian>(part.denomination)?;
    Optional::write(&mut writer, part.note.as_ref(), |mut w, note| {
        note.output_id.txid().write(&mut w)?;
        w.write_u32::<LittleEndian>(note.output_id.output_index())?;
        w.write_all(&note.nullifier)?;
        w.write_all(&note.commitment)
    })?;
    Optional::write(&mut writer, part.bucket_index, |w, bucket_index| {
        w.write_u64::<LittleEndian>(bucket_index)
    })?;
    Optional::write(&mut writer, part.anchor_bucket, |w, anchor_bucket| {
        w.write_u64::<LittleEndian>(anchor_bucket)
    })?;
    Optional::write(&mut writer, part.target_height, |w, target_height| {
        w.write_u32::<LittleEndian>(target_height.into())
    })?;
    match part.state {
        PartState::Bound => writer.write_u8(0)?,
        PartState::Assigned => writer.write_u8(1)?,
        PartState::Signed => writer.write_u8(2)?,
        PartState::Broadcast => writer.write_u8(3)?,
        PartState::Confirmed { height } => {
            writer.write_u8(4)?;
            writer.write_u32::<LittleEndian>(height.into())?;
        }
        PartState::Expired => writer.write_u8(5)?,
        PartState::Invalidated => writer.write_u8(6)?,
    }
    Optional::write(&mut writer, part.txid, |w, txid| txid.write(w))?;
    Optional::write(&mut writer, part.expiry_height, |w, expiry_height| {
        w.write_u32::<LittleEndian>(expiry_height.into())
    })?;
    Optional::write(&mut writer, part.signed_blob.as_ref(), |w, signed_blob| {
        Vector::write(w, signed_blob, |w, byte| w.write_u8(*byte))
    })?;
    Optional::write(
        &mut writer,
        part.anchor_witness.as_ref(),
        |mut w, witness| {
            w.write_all(&witness.anchor)?;
            w.write_u64::<LittleEndian>(witness.position)?;
            Vector::write(&mut w, &witness.auth_path, |w, node| w.write_all(node))
        },
    )?;
    writer.write_u8(part.attempts)
}

fn read_part<R: Read>(mut reader: R, inner_version: u8) -> io::Result<PartRecord> {
    let id = PartId(reader.read_u32::<LittleEndian>()?);
    let denomination = reader.read_u64::<LittleEndian>()?;
    let note = Optional::read(&mut reader, |mut r| {
        let txid = TxId::read(&mut r)?;
        let output_index = r.read_u32::<LittleEndian>()?;
        let mut nullifier = [0u8; 32];
        r.read_exact(&mut nullifier)?;
        let mut commitment = [0u8; 32];
        r.read_exact(&mut commitment)?;
        Ok(BoundNote {
            output_id: OutputId::new(txid, output_index),
            nullifier,
            commitment,
        })
    })?;
    let bucket_index = Optional::read(&mut reader, |r| r.read_u64::<LittleEndian>())?;
    let stored_anchor_bucket = if inner_version >= 4 {
        Optional::read(&mut reader, |r| r.read_u64::<LittleEndian>())?
    } else {
        None
    };
    let target_height = if inner_version >= 1 {
        Optional::read(&mut reader, |r| {
            Ok(BlockHeight::from_u32(r.read_u32::<LittleEndian>()?))
        })?
    } else {
        None
    };
    let state = match reader.read_u8()? {
        0 => PartState::Bound,
        1 => PartState::Assigned,
        2 => PartState::Signed,
        3 => PartState::Broadcast,
        4 => PartState::Confirmed {
            height: BlockHeight::from_u32(reader.read_u32::<LittleEndian>()?),
        },
        5 => PartState::Expired,
        6 => PartState::Invalidated,
        other => {
            return Err(Error::new(
                ErrorKind::InvalidData,
                format!("invalid part state {other}"),
            ));
        }
    };
    let txid = Optional::read(&mut reader, TxId::read)?;
    let expiry_height = Optional::read(&mut reader, |r| {
        Ok(BlockHeight::from_u32(r.read_u32::<LittleEndian>()?))
    })?;
    let signed_blob = Optional::read(&mut reader, |r| {
        Vector::read(r, byteorder::ReadBytesExt::read_u8)
    })?;
    let anchor_witness = Optional::read(&mut reader, |mut r| {
        let mut anchor = [0u8; 32];
        r.read_exact(&mut anchor)?;
        let position = r.read_u64::<LittleEndian>()?;
        let auth_path = Vector::read(&mut r, |r| {
            let mut node = [0u8; 32];
            r.read_exact(&mut node)?;
            Ok(node)
        })?;
        Ok(BoundaryWitness {
            anchor,
            position,
            auth_path,
        })
    })?;
    let attempts = reader.read_u8()?;

    // Before version 4 the anchor *was* the transmission window's boundary, an
    // age of zero. A part that already carries a transaction committed to
    // that anchor keeps it: the signature cannot be re-aimed, so recording
    // anything else would misdescribe what is on the wire. An unsigned part
    // has committed to nothing, so it is left anchorless and the next
    // placement (or `refresh_part_witnesses`) draws it a legal age (ADR 0018).
    //
    // Its cached witness goes with it. That witness proves the note under the
    // *window's* boundary, which is not where the part will anchor once an
    // age is drawn, so keeping it would either fail to prove or quietly prove
    // against the age-zero anchor this change exists to retire.
    let (anchor_bucket, anchor_witness) = if inner_version >= 4 {
        (stored_anchor_bucket, anchor_witness)
    } else {
        match state {
            PartState::Signed | PartState::Broadcast | PartState::Confirmed { .. } => {
                (bucket_index, anchor_witness)
            }
            PartState::Bound
            | PartState::Assigned
            | PartState::Expired
            | PartState::Invalidated => (None, None),
        }
    };

    Ok(PartRecord {
        id,
        denomination,
        note,
        bucket_index,
        anchor_bucket,
        target_height,
        state,
        txid,
        expiry_height,
        signed_blob,
        anchor_witness,
        attempts,
    })
}

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

    fn arbitrary_params() -> impl Strategy<Value = MigrationParams> {
        (
            any::<u32>(),
            proptest::collection::vec(1u64..=10_000_000_000, 1..8),
            any::<u64>(),
            any::<u64>(),
            any::<u64>(),
            any::<u32>(),
            any::<u32>(),
            any::<u32>(),
            1usize..=1000,
            any::<u64>(),
        )
            .prop_map(
                |(
                    version,
                    denominations,
                    denom_cap,
                    max_residual_value,
                    sweep_min,
                    bucket_modulus,
                    k_max,
                    target_sessions,
                    max_actions_per_split_tx,
                    part_fee,
                )| MigrationParams {
                    version,
                    denominations,
                    denom_cap,
                    max_residual_value,
                    sweep_min,
                    bucket_modulus,
                    k_max,
                    target_sessions,
                    max_actions_per_split_tx,
                    part_fee,
                },
            )
    }

    fn arbitrary_txid() -> impl Strategy<Value = TxId> {
        any::<[u8; 32]>().prop_map(TxId::from_bytes)
    }

    fn arbitrary_state() -> impl Strategy<Value = PartState> {
        prop_oneof![
            Just(PartState::Bound),
            Just(PartState::Assigned),
            Just(PartState::Signed),
            Just(PartState::Broadcast),
            any::<u32>().prop_map(|h| PartState::Confirmed {
                height: BlockHeight::from_u32(h)
            }),
            Just(PartState::Expired),
            Just(PartState::Invalidated),
        ]
    }

    fn arbitrary_part() -> impl Strategy<Value = PartRecord> {
        (
            (
                any::<u32>(),
                any::<u64>(),
                proptest::option::of((
                    arbitrary_txid(),
                    any::<u32>(),
                    any::<[u8; 32]>(),
                    any::<[u8; 32]>(),
                )),
                proptest::option::of(any::<u64>()),
                proptest::option::of(any::<u32>()),
                arbitrary_state(),
            ),
            (
                proptest::option::of(arbitrary_txid()),
                proptest::option::of(any::<u32>()),
                proptest::option::of(proptest::collection::vec(any::<u8>(), 0..64)),
                proptest::option::of((
                    any::<[u8; 32]>(),
                    any::<u64>(),
                    proptest::collection::vec(any::<[u8; 32]>(), 0..32),
                )),
                any::<u8>(),
                proptest::option::of(any::<u64>()),
            ),
        )
            .prop_map(
                |(
                    (id, denomination, note, bucket_index, target_height, state),
                    (txid, expiry_height, signed_blob, anchor_witness, attempts, anchor_bucket),
                )| PartRecord {
                    id: PartId(id),
                    denomination,
                    note: note.map(|(txid, output_index, nullifier, commitment)| BoundNote {
                        output_id: OutputId::new(txid, output_index),
                        nullifier,
                        commitment,
                    }),
                    bucket_index,
                    anchor_bucket,
                    target_height: target_height.map(BlockHeight::from_u32),
                    state,
                    txid,
                    expiry_height: expiry_height.map(BlockHeight::from_u32),
                    signed_blob,
                    anchor_witness: anchor_witness.map(|(anchor, position, auth_path)| {
                        BoundaryWitness {
                            anchor,
                            position,
                            auth_path,
                        }
                    }),
                    attempts,
                },
            )
    }

    fn arbitrary_phase() -> impl Strategy<Value = MigrationPhase> {
        prop_oneof![
            Just(MigrationPhase::Planned),
            (
                any::<u32>(),
                proptest::collection::vec(arbitrary_txid(), 0..5)
            )
                .prop_map(|(round, pending_txids)| MigrationPhase::NoteSplitting {
                    round,
                    pending_txids
                }),
            Just(MigrationPhase::PartsScheduled),
            any::<u64>().prop_map(|residual| MigrationPhase::Complete { residual }),
        ]
    }

    fn arbitrary_migration_state() -> impl Strategy<Value = MigrationState> {
        (
            arbitrary_params(),
            any::<[u8; 32]>(),
            any::<[u8; 32]>(),
            any::<u64>(),
            any::<bool>(),
            any::<bool>(),
            0u32..(1 << 31),
            arbitrary_phase(),
            proptest::collection::vec(arbitrary_part(), 0..12),
        )
            .prop_map(
                |(
                    params,
                    params_hash,
                    plan_hash,
                    consented_at,
                    lazy,
                    immediate,
                    account,
                    phase,
                    parts,
                )| {
                    MigrationState {
                        params,
                        consent: ConsentBinding {
                            params_hash,
                            plan_hash,
                            consented_at,
                        },
                        strategy: if lazy {
                            SigningStrategy::LazyAtBoundary
                        } else {
                            SigningStrategy::PreSigned
                        },
                        mode: if immediate {
                            MigrationMode::Immediate
                        } else {
                            MigrationMode::Scheduled
                        },
                        account: zip32::AccountId::try_from(account).expect("in range"),
                        phase,
                        parts,
                    }
                },
            )
    }

    proptest! {
        #[test]
        fn round_trips(state in arbitrary_migration_state()) {
            let mut bytes = Vec::new();
            write(&mut bytes, &state).expect("writes");
            let recovered = read(bytes.as_slice()).expect("reads");
            prop_assert_eq!(state, recovered);
        }
    }

    /// A freshly planned mainnet state, the smallest well-formed fixture.
    fn planned_state() -> MigrationState {
        MigrationState {
            params: MigrationParams::provisional(crate::config::ChainType::Mainnet),
            consent: ConsentBinding {
                params_hash: [0; 32],
                plan_hash: [0; 32],
                consented_at: 0,
            },
            strategy: SigningStrategy::LazyAtBoundary,
            mode: MigrationMode::Scheduled,
            account: zip32::AccountId::ZERO,
            phase: MigrationPhase::Planned,
            parts: Vec::new(),
        }
    }

    #[test]
    fn unknown_inner_version_is_rejected() {
        let mut bytes = Vec::new();
        write(&mut bytes, &planned_state()).expect("writes");
        bytes[0] = INNER_VERSION + 1;
        assert!(read(bytes.as_slice()).is_err());
    }

    /// Relative to v3, a v1 blob carries the retired `expiry_delta` u32
    /// before `part_fee` and lacks the trailing mode byte. Reading it must
    /// succeed, discard the delta, and default the mode to `Scheduled`, the
    /// conservative reading that makes the immediate path refuse to
    /// collapse an old persisted state.
    #[test]
    fn v1_blob_reads_with_scheduled_mode() {
        let mut state = planned_state();
        state.mode = MigrationMode::Immediate;
        let mut bytes = Vec::new();
        write(&mut bytes, &state).expect("writes");
        bytes[0] = 1;
        bytes.pop();
        // Splice the legacy expiry_delta back in where v1 carried it: after
        // the fixed-width params fields that follow the denominations vector.
        let offset = 1 + 4 + 1 + 8 * state.params.denominations.len() + 3 * 8 + 3 * 4 + 8;
        bytes.splice(offset..offset, 296u32.to_le_bytes());

        let recovered = read(bytes.as_slice()).expect("a v1 blob still reads");
        assert_eq!(recovered.mode, MigrationMode::Scheduled);
        state.mode = MigrationMode::Scheduled;
        assert_eq!(recovered, state);
    }

    /// Before version 4 a part's anchor was its transmission window's boundary,
    /// an age of zero. Reading such a part must sort it by whether a
    /// transaction already commits to that anchor: a `Signed` part keeps it,
    /// because its signature cannot be re-aimed, while an unsigned one is left
    /// anchorless so the next placement draws it a legal age. The unsigned
    /// part's cached witness must go too — it proves the note under the
    /// window's boundary, so surviving into a redrawn anchor would either fail
    /// to prove or quietly resurrect the age-zero anchor (ADR 0018).
    #[test]
    fn a_v3_blob_keeps_signed_anchors_and_drops_unsigned_ones() {
        let witness = BoundaryWitness {
            anchor: [7; 32],
            position: 11,
            auth_path: vec![[3; 32]],
        };
        // A v3 part's anchor *is* its bucket_index, so the fixture writes
        // them equal; the sentinel only has to be locatable in the stream.
        const BUCKET: u64 = 0x0BAD_C0DE;
        let with_state = |state: PartState| {
            let mut part = PartRecord::new(
                PartId(0),
                1_000_000,
                BoundNote {
                    output_id: OutputId::new(TxId::from_bytes([1; 32]), 0),
                    nullifier: [0; 32],
                    commitment: [0; 32],
                },
            );
            part.bucket_index = Some(BUCKET);
            part.anchor_bucket = Some(BUCKET);
            part.anchor_witness = Some(witness.clone());
            part.state = state;
            let mut state_with_part = planned_state();
            state_with_part.parts = vec![part];
            let mut bytes = Vec::new();
            write(&mut bytes, &state_with_part).expect("writes");

            // Re-label as v3 and strip the field the v4 layout added: the
            // `Optional` tag and payload of the *second* of the two adjacent
            // identical encodings, which is `anchor_bucket`.
            bytes[0] = 3;
            let field = [&[1u8][..], &BUCKET.to_le_bytes()[..]].concat();
            let first = bytes
                .windows(field.len())
                .position(|window| window == field)
                .expect("bucket_index is in the stream");
            let anchor_at = first + field.len();
            assert_eq!(
                &bytes[anchor_at..anchor_at + field.len()],
                field.as_slice(),
                "anchor_bucket is written immediately after bucket_index"
            );
            bytes.drain(anchor_at..anchor_at + field.len());
            read(bytes.as_slice()).expect("a v3 blob still reads").parts
        };

        let signed = with_state(PartState::Signed);
        assert_eq!(
            signed[0].anchor_bucket,
            Some(BUCKET),
            "a signed part keeps the age-zero anchor its transaction commits"
        );
        assert_eq!(
            signed[0].anchor_witness.as_ref(),
            Some(&witness),
            "and keeps the witness that proves it"
        );

        let assigned = with_state(PartState::Assigned);
        assert_eq!(
            assigned[0].anchor_bucket, None,
            "an unsigned part is left anchorless for a fresh draw"
        );
        assert_eq!(
            assigned[0].anchor_witness, None,
            "and loses the witness aimed at the window's boundary"
        );
    }

    /// The `as usize` cast reading `max_actions_per_split_tx` silently
    /// truncates on 32-bit targets. This test patches a serialized stream so
    /// the persisted value exceeds `u32::MAX`: the read must either reject
    /// the stream (the desired `usize::try_from` + `InvalidData` behavior)
    /// or preserve the value. It passes vacuously on 64-bit hosts. Run under
    /// a 32-bit target (e.g. i686-unknown-linux-gnu) to observe the failure.
    /// Every bucket computation divides or multiplies by the modulus, so a
    /// zero arriving from a corrupt wallet file must fail the read typed
    /// rather than panic downstream bucket arithmetic.
    #[test]
    fn zero_bucket_modulus_is_rejected_at_read() {
        let mut state = planned_state();
        state.params.bucket_modulus = 0;

        let mut bytes = Vec::new();
        write(&mut bytes, &state).expect("writes");

        let error = read(bytes.as_slice()).expect_err("a zero modulus must not read");
        assert_eq!(error.kind(), ErrorKind::InvalidData);
    }

    #[test]
    fn max_actions_read_never_silently_truncates() {
        const SENTINEL: u64 = 0x1122_3344;
        const PATCHED: u64 = 0x1_1122_3344; // does not fit in u32

        let mut state = planned_state();
        state.params.max_actions_per_split_tx = SENTINEL as usize;

        let mut bytes = Vec::new();
        write(&mut bytes, &state).expect("writes");

        // Locate the sentinel's unique little-endian encoding and set a high
        // byte, producing the stream a 64-bit writer (or corruption) would
        // carry.
        let needle = SENTINEL.to_le_bytes();
        let position = bytes
            .windows(8)
            .position(|window| window == needle)
            .expect("sentinel is unique in the fixture");
        bytes[position..position + 8].copy_from_slice(&PATCHED.to_le_bytes());

        match read(bytes.as_slice()) {
            Err(error) => assert_eq!(error.kind(), ErrorKind::InvalidData),
            Ok(read_state) => assert_eq!(
                read_state.params.max_actions_per_split_tx as u64, PATCHED,
                "read silently truncated the persisted value"
            ),
        }
    }
}