eth-state-diff 0.2.3

Fork-aware, domain-specific delta encoding for Ethereum consensus-layer state.
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
//! Delta encoding and reconstruction for Ethereum validator registries.
//!
//! This module computes compact [`ValidatorsDiff`] values between two validator
//! registries and applies those deltas to reconstruct the target registry.
//!
//! Validator records are fixed-width in their consensus SSZ representation,
//! with [`VALIDATOR_SSZ_SIZE`] bytes per validator. The delta format avoids
//! storing complete validator records when only individual fields have
//! changed.
//!
//! ## What is encoded
//!
//! For validators present in both the base and target registries, the encoder
//! stores patches only for fields whose values changed:
//!
//! - [`ValidatorField::WithdrawalCredentials`]
//! - [`ValidatorField::EffectiveBalance`]
//! - [`ValidatorField::Slashed`]
//! - [`ValidatorField::ActivationEligibilityEpoch`]
//! - [`ValidatorField::ActivationEpoch`]
//! - [`ValidatorField::ExitEpoch`]
//! - [`ValidatorField::WithdrawableEpochSlashed`]
//!
//! Validators that exist only in the target registry are stored as their raw
//! SSZ representations in [`ValidatorsDiff::appended_validators`].
//!
//! The `pubkey` field is not patched because validator public keys are
//! immutable after registration.
//!
//! ## Withdrawable epoch
//!
//! `withdrawable_epoch` is handled specially because its value is derivable
//! for non-slashed validators. When `exit_epoch` changes on a non-slashed
//! validator, the application side reconstructs:
//!
//! ```text
//! withdrawable_epoch = exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY
//! ```
//!
//! For slashed validators, `withdrawable_epoch` is explicitly encoded because
//! it is not reconstructed from `exit_epoch` alone.
//!
//! This makes the delta smaller while preserving the target validator state.
//!
//! ## Two integration APIs
//!
//! The module provides two equivalent APIs for different validator storage
//! layouts.
//!
//! ### Contiguous SSZ storage
//!
//! [`diff_validators`] and [`apply_validators`] operate directly on
//! `Vec<u8>`/byte slices containing consecutive SSZ validator records.
//!
//! This is useful for clients that keep their validator registry in a flat
//! SSZ-compatible representation.
//!
//! ### Native client storage
//!
//! [`diff_validators_iter`] and [`apply_validators_iter`] operate through
//! [`ValidatorSnapshot`] and [`ValidatorMutTarget`].
//!
//! This allows a consensus client to diff and reconstruct validators without
//! first converting its native data structure into one large byte buffer.
//!
//! The iterator API is particularly useful for clients whose validator
//! registry is backed by persistent lists, trees, or other non-contiguous
//! structures.
//!
//! ## SSZ representation
//!
//! The flat representation assumed by this module is the canonical
//! consensus-layer validator SSZ layout:
//!
//! | Offset | Size | Field |
//! |---:|---:|---|
//! | `0` | `48` | `pubkey` |
//! | `48` | `32` | `withdrawal_credentials` |
//! | `80` | `8` | `effective_balance` |
//! | `88` | `1` | `slashed` |
//! | `89` | `8` | `activation_eligibility_epoch` |
//! | `97` | `8` | `activation_epoch` |
//! | `105` | `8` | `exit_epoch` |
//! | `113` | `8` | `withdrawable_epoch` |
//!
//! The total size is [`VALIDATOR_SSZ_SIZE`] bytes.
//!
//! ## Complexity
//!
//! Diffing is linear in the number of validators:
//!
//! ```text
//! O(min(base_len, target_len) + appended_validators)
//! ```
//!
//! Applying a delta is linear in the number of patches plus the number of
//! appended validators:
//!
//! ```text
//! O(patches + appended_validators)
//! ```
//!
//! The contiguous byte implementation performs in-place mutation and does not
//! require rebuilding the existing validator registry.
//!
//! ## Delta validity
//!
//! [`apply_validators`] and [`apply_validators_iter`] assume that the supplied
//! delta was produced for the corresponding base validator registry.
//! Application does not independently verify that every patch matches the
//! expected base value.
//!
//! Patch values are validated for the width required by their corresponding
//! [`ValidatorField`]. Invalid patch data is reported as
//! [`Error::MalformedDelta`] rather than causing reconstruction to panic.
//!
//! A patch referring to a validator index that does not exist in the target
//! collection is reported as [`Error::InvalidDelta`].
//!
//! Appended validator data must contain complete
//! [`VALIDATOR_SSZ_SIZE`]-byte SSZ records.
//!
//! [`ValidatorsDiff`]  
//! [`ValidatorField`]  
//! [`ValidatorSnapshot`]  
//! [`ValidatorMut`]  
//! [`ValidatorMutTarget`]  
//! [`VALIDATOR_SSZ_SIZE`]  
//! [`MIN_VALIDATOR_WITHDRAWABILITY_DELAY`]  

use crate::{
    error::Error,
    types::{
        ArchivedValidatorField, ArchivedValidatorsDiff, ValidatorField, ValidatorPatch,
        ValidatorsDiff, MIN_VALIDATOR_WITHDRAWABILITY_DELAY, VALIDATOR_SSZ_SIZE,
    },
};

/// Read-only view of a validator used by the delta encoder.
///
/// Implementations provide access to the validator fields that can participate
/// in a delta. The trait deliberately does not require a concrete validator
/// type, allowing the same diff algorithm to operate on both flat SSZ records
/// and native consensus-client data structures.
///
/// [`to_ssz_bytes`](Self::to_ssz_bytes) is only required when a validator is
/// present in the target registry but not in the base registry.
pub trait ValidatorSnapshot {
    fn withdrawal_credentials(&self) -> &[u8; 32];
    fn effective_balance(&self) -> u64;
    fn is_slashed(&self) -> bool;
    fn activation_eligibility_epoch(&self) -> u64;
    fn activation_epoch(&self) -> u64;
    fn exit_epoch(&self) -> u64;
    fn withdrawable_epoch(&self) -> u64;

    /// Serializes the validator to its consensus SSZ representation.
    /// Only required for validators appended to the target registry.
    fn to_ssz_bytes(&self) -> Vec<u8>;
}

/// Mutable view of a validator used during delta reconstruction.
///
/// Implementations expose the fields that may be modified by a
/// [`ValidatorField`] patch.
///
/// The current slashed status is required so that applying an `exit_epoch`
/// patch can deterministically reconstruct `withdrawable_epoch` for
/// non-slashed validators.
pub trait ValidatorMut {
    /// Returns the current slashed status. Required for deterministic
    /// reconstruction of `withdrawable_epoch` when `exit_epoch` changes.
    fn is_slashed(&self) -> bool;

    fn set_withdrawal_credentials(&mut self, value: &[u8; 32]);
    fn set_effective_balance(&mut self, value: u64);
    fn set_slashed(&mut self, value: bool);
    fn set_activation_eligibility_epoch(&mut self, value: u64);
    fn set_activation_epoch(&mut self, value: u64);
    fn set_exit_epoch(&mut self, value: u64);
    fn set_withdrawable_epoch(&mut self, value: u64);
}

/// Mutable access to a validator collection used during reconstruction.
///
/// This trait abstracts over the client's validator storage representation.
/// Implementations may back the collection with a contiguous vector, a
/// persistent list, a tree, or another native data structure.
///
/// The collection is expected to preserve validator ordering: validator index
/// `i` in the delta must refer to the same validator index `i` in the target
/// collection.
///
/// New validators are supplied as complete consensus SSZ records through
/// [`push_from_ssz`](Self::push_from_ssz).
pub trait ValidatorMutTarget {
    type Validator<'a>: ValidatorMut
    where
        Self: 'a;

    /// Fetches a mutable validator view by index.
    fn get_mut(&mut self, index: usize) -> Option<Self::Validator<'_>>;

    /// Appends a newly seen validator from its raw SSZ bytes.
    fn push_from_ssz(&mut self, ssz_bytes: &[u8]);
}

/// Computes a compact validator delta from two contiguous SSZ byte buffers.
///
/// Both buffers must contain zero or more complete validator records, with
/// each record occupying exactly [`VALIDATOR_SSZ_SIZE`] bytes.
///
/// The resulting [`ValidatorsDiff`] contains:
///
/// - field-level patches for validators present in both buffers; and
/// - complete SSZ records for validators appended to the target buffer.
///
/// The function does not allocate or deserialize individual validator
/// structures while scanning the common portion of the buffers. Fields are
/// read directly from their fixed offsets in the SSZ representation.
///
/// # Examples
///
/// A delta can be applied to the original buffer to reconstruct the target:
///
/// ```ignore
/// let delta = diff_validators(&base, &target);
/// apply_validators(&mut base, &delta);
///
/// assert_eq!(base, target);
/// ```
///
/// [`VALIDATOR_SSZ_SIZE`]: crate::types::VALIDATOR_SSZ_SIZE
pub fn diff_validators(base_bytes: &[u8], target_bytes: &[u8]) -> ValidatorsDiff {
    diff_validators_impl(
        base_bytes
            .chunks_exact(VALIDATOR_SSZ_SIZE)
            .map(ByteValidator::new),
        target_bytes
            .chunks_exact(VALIDATOR_SSZ_SIZE)
            .map(ByteValidator::new),
    )
}

/// Computes a compact validator delta using client-provided validator views.
///
/// This is the native-storage counterpart to [`diff_validators`]. Instead of
/// requiring the validator registries to be represented as contiguous SSZ
/// buffers, the caller supplies iterators of [`ValidatorSnapshot`] values.
///
/// Only the fields exposed by [`ValidatorSnapshot`] are inspected. Validators
/// that occur only in the target iterator are serialized through
/// [`ValidatorSnapshot::to_ssz_bytes`] and stored in the resulting delta.
///
/// The iterators must report their exact validator counts through
/// [`ExactSizeIterator`].
///
/// This function is useful when a consensus client stores validators in a
/// persistent list, tree, or another non-contiguous data structure and wants
/// to avoid materializing the complete registry as SSZ bytes.
///
/// [`diff_validators`]
/// [`ValidatorSnapshot`]
pub fn diff_validators_iter<I1, I2, V1, V2>(base: I1, target: I2) -> ValidatorsDiff
where
    I1: ExactSizeIterator<Item = V1>,
    I2: ExactSizeIterator<Item = V2>,
    V1: ValidatorSnapshot,
    V2: ValidatorSnapshot,
{
    diff_validators_impl(base, target)
}

/// The core diffing algorithm, agnostic to the input memory layout.
fn diff_validators_impl<I1, I2, V1, V2>(mut base: I1, mut target: I2) -> ValidatorsDiff
where
    I1: ExactSizeIterator<Item = V1>,
    I2: ExactSizeIterator<Item = V2>,
    V1: ValidatorSnapshot,
    V2: ValidatorSnapshot,
{
    let mut patches = Vec::with_capacity(512);
    let mut appended_validators = Vec::new();

    for (i, (b, t)) in base.by_ref().zip(target.by_ref()).enumerate() {
        let wc = t.withdrawal_credentials();
        let eb = t.effective_balance();
        let slashed = t.is_slashed();
        let aee = t.activation_eligibility_epoch();
        let ae = t.activation_epoch();
        let ee = t.exit_epoch();

        if b.withdrawal_credentials() == wc
            && b.effective_balance() == eb
            && b.is_slashed() == slashed
            && b.activation_eligibility_epoch() == aee
            && b.activation_epoch() == ae
            && b.exit_epoch() == ee
            && (!slashed || b.withdrawable_epoch() == t.withdrawable_epoch())
        {
            continue;
        }

        let index = u32::try_from(i).expect("validator index exceeds u32 range");

        if b.withdrawal_credentials() != wc {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::WithdrawalCredentials,
                value: wc.to_vec(),
            });
        }
        if b.effective_balance() != eb {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::EffectiveBalance,
                value: eb.to_le_bytes().to_vec(),
            });
        }
        if b.is_slashed() != slashed {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::Slashed,
                value: vec![slashed as u8],
            });
        }
        if b.activation_eligibility_epoch() != aee {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::ActivationEligibilityEpoch,
                value: aee.to_le_bytes().to_vec(),
            });
        }
        if b.activation_epoch() != ae {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::ActivationEpoch,
                value: ae.to_le_bytes().to_vec(),
            });
        }
        if b.exit_epoch() != ee {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::ExitEpoch,
                value: ee.to_le_bytes().to_vec(),
            });
        }
        if slashed && b.withdrawable_epoch() != t.withdrawable_epoch() {
            patches.push(ValidatorPatch {
                index,
                field: ValidatorField::WithdrawableEpochSlashed,
                value: t.withdrawable_epoch().to_le_bytes().to_vec(),
            });
        }
    }

    for t_val in target {
        appended_validators.extend(t_val.to_ssz_bytes());
    }

    ValidatorsDiff {
        patches,
        appended_validators,
    }
}

/// Applies a validator delta to a contiguous SSZ byte buffer in place.
///
/// The buffer must represent the same base validator registry against which
/// the delta was generated.
///
/// Existing validators are modified according to the delta's field patches.
/// Newly appended validators are added from their raw SSZ representations.
///
/// This function does not require deserializing the validator registry into
/// Rust validator structures. Existing records are modified directly at their
/// fixed SSZ offsets.
///
/// # Errors
///
/// Returns [`Error::MalformedDelta`] if a patch contains a value with an
/// invalid width for its field.
///
/// Returns [`Error::InvalidDelta`] if a patch refers to a validator index
/// that does not exist in the buffer.
///
/// # Correctness
///
/// The delta is expected to have been generated from the same base registry.
/// This function does not verify that the current contents of the buffer
/// correspond to the original base state.
///
/// [`ArchivedValidatorsDiff`]: crate::types::ArchivedValidatorsDiff
/// [`Error`]: crate::Error
pub fn apply_validators(base: &mut Vec<u8>, delta: &ArchivedValidatorsDiff) -> Result<(), Error> {
    apply_validators_iter(&mut ByteValidatorTarget(base), delta)
}

/// Applies a validator delta directly to a client's native validator
/// collection.
///
/// The target collection is accessed through [`ValidatorMutTarget`], allowing
/// the caller to mutate validators without converting the entire registry
/// into a contiguous SSZ byte buffer.
///
/// For every patch, the corresponding validator is obtained with
/// [`ValidatorMutTarget::get_mut`] and the specified field is updated.
///
/// Newly appended validators are passed to
/// [`ValidatorMutTarget::push_from_ssz`] as complete
/// [`VALIDATOR_SSZ_SIZE`]-byte SSZ records.
///
/// For a non-slashed validator whose `exit_epoch` is patched, the
/// `withdrawable_epoch` is reconstructed automatically as:
///
/// ```text
/// exit_epoch + MIN_VALIDATOR_WITHDRAWABILITY_DELAY
/// ```
///
/// For slashed validators, `withdrawable_epoch` is restored explicitly from
/// the [`ValidatorField::WithdrawableEpochSlashed`] patch.
///
/// # Errors
///
/// Returns [`Error::MalformedDelta`] if a patch contains a value with an
/// invalid width for its field.
///
/// Returns [`Error::InvalidDelta`] if a patch refers to a validator index
/// that does not exist in the target collection.
///
/// [`ValidatorMutTarget`]: crate::validators::ValidatorMutTarget
/// [`ValidatorField::WithdrawableEpochSlashed`]:
///     crate::types::ValidatorField::WithdrawableEpochSlashed
/// [`VALIDATOR_SSZ_SIZE`]: crate::types::VALIDATOR_SSZ_SIZE
/// [`MIN_VALIDATOR_WITHDRAWABILITY_DELAY`]:
///     crate::types::MIN_VALIDATOR_WITHDRAWABILITY_DELAY
/// [`Error`]: crate::Error
pub fn apply_validators_iter<T: ValidatorMutTarget>(
    target: &mut T,
    delta: &ArchivedValidatorsDiff,
) -> Result<(), Error> {
    for patch in delta.patches.iter() {
        let idx = patch.index.to_native() as usize;
        let val_bytes = patch.value.as_slice();

        let mut validator = target.get_mut(idx).ok_or_else(|| {
            Error::InvalidDelta(format!("validator patch index {idx} is out of bounds"))
        })?;

        match &patch.field {
            ArchivedValidatorField::WithdrawalCredentials => {
                let bytes: [u8; 32] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "withdrawal credentials patch has invalid width: \
                         expected 32 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                validator.set_withdrawal_credentials(&bytes);
            }
            ArchivedValidatorField::EffectiveBalance => {
                let bytes: [u8; 8] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "effective balance patch has invalid width: \
                         expected 8 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                let eb = u64::from_le_bytes(bytes);
                validator.set_effective_balance(eb);
            }
            ArchivedValidatorField::Slashed => {
                let [value] = <[u8; 1]>::try_from(val_bytes).map_err(|_| {
                    Error::MalformedDelta(format!(
                        "slashed patch has invalid width: expected 1 byte, got {}",
                        val_bytes.len()
                    ))
                })?;

                validator.set_slashed(value != 0);
            }
            ArchivedValidatorField::ActivationEligibilityEpoch => {
                let bytes: [u8; 8] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "activation eligibility epoch patch has invalid width: \
                         expected 8 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                let epoch = u64::from_le_bytes(bytes);
                validator.set_activation_eligibility_epoch(epoch);
            }
            ArchivedValidatorField::ActivationEpoch => {
                let bytes: [u8; 8] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "activation epoch patch has invalid width: \
                         expected 8 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                let epoch = u64::from_le_bytes(bytes);
                validator.set_activation_epoch(epoch);
            }
            ArchivedValidatorField::ExitEpoch => {
                let bytes: [u8; 8] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "exit epoch patch has invalid width: \
                         expected 8 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                let ee = u64::from_le_bytes(bytes);
                validator.set_exit_epoch(ee);

                // Deterministic reconstruction for non-slashed validators.
                if !validator.is_slashed() {
                    let we = ee.saturating_add(MIN_VALIDATOR_WITHDRAWABILITY_DELAY);
                    validator.set_withdrawable_epoch(we);
                }
            }
            ArchivedValidatorField::WithdrawableEpochSlashed => {
                let bytes: [u8; 8] = val_bytes.try_into().map_err(|_| {
                    Error::MalformedDelta(format!(
                        "withdrawable epoch patch has invalid width: \
                         expected 8 bytes, got {}",
                        val_bytes.len()
                    ))
                })?;

                let we = u64::from_le_bytes(bytes);
                validator.set_withdrawable_epoch(we);
            }
        }
    }

    if delta.appended_validators.len() % VALIDATOR_SSZ_SIZE != 0 {
        return Err(Error::MalformedDelta(
            "appended validator data does not contain complete SSZ records".into(),
        ));
    }

    for chunk in delta
        .appended_validators
        .as_slice()
        .chunks_exact(VALIDATOR_SSZ_SIZE)
    {
        target.push_from_ssz(chunk);
    }

    Ok(())
}

/// A zero-cost wrapper that allows byte slices to implement
/// [`ValidatorSnapshot`].
///
/// The wrapped slice must contain exactly one complete validator SSZ record.
struct ByteValidator<'a>(&'a [u8]);

impl<'a> ByteValidator<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        debug_assert_eq!(
            bytes.len(),
            VALIDATOR_SSZ_SIZE,
            "ByteValidator must contain exactly one complete SSZ validator record",
        );

        Self(bytes)
    }

    #[inline]
    fn bytes<const N: usize>(&self, start: usize) -> [u8; N] {
        self.0
            .get(start..start + N)
            .and_then(|bytes| bytes.try_into().ok())
            .expect("ByteValidator contains a complete SSZ validator record")
    }
}

impl<'a> ValidatorSnapshot for ByteValidator<'a> {
    #[inline]
    fn withdrawal_credentials(&self) -> &[u8; 32] {
        self.0
            .get(48..80)
            .and_then(|bytes| bytes.try_into().ok())
            .expect("ByteValidator contains a complete SSZ validator record")
    }

    #[inline]
    fn effective_balance(&self) -> u64 {
        u64::from_le_bytes(self.bytes::<8>(80))
    }

    #[inline]
    fn is_slashed(&self) -> bool {
        self.bytes::<1>(88)[0] != 0
    }

    #[inline]
    fn activation_eligibility_epoch(&self) -> u64 {
        u64::from_le_bytes(self.bytes::<8>(89))
    }

    #[inline]
    fn activation_epoch(&self) -> u64 {
        u64::from_le_bytes(self.bytes::<8>(97))
    }

    #[inline]
    fn exit_epoch(&self) -> u64 {
        u64::from_le_bytes(self.bytes::<8>(105))
    }

    #[inline]
    fn withdrawable_epoch(&self) -> u64 {
        u64::from_le_bytes(self.bytes::<8>(113))
    }

    #[inline]
    fn to_ssz_bytes(&self) -> Vec<u8> {
        self.0.to_vec()
    }
}

/// Mutable byte slice wrapper implementing `ValidatorMut`.
struct ByteValidatorMut<'a>(&'a mut [u8]);

impl<'a> ValidatorMut for ByteValidatorMut<'a> {
    #[inline]
    fn is_slashed(&self) -> bool {
        *self
            .0
            .get(88)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            != 0
    }

    #[inline]
    fn set_withdrawal_credentials(&mut self, v: &[u8; 32]) {
        self.0
            .get_mut(48..80)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(v);
    }

    #[inline]
    fn set_effective_balance(&mut self, v: u64) {
        self.0
            .get_mut(80..88)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(&v.to_le_bytes());
    }

    #[inline]
    fn set_slashed(&mut self, v: bool) {
        *self
            .0
            .get_mut(88)
            .expect("ByteValidatorMut contains a complete SSZ validator record") = v as u8;
    }

    #[inline]
    fn set_activation_eligibility_epoch(&mut self, v: u64) {
        self.0
            .get_mut(89..97)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(&v.to_le_bytes());
    }

    #[inline]
    fn set_activation_epoch(&mut self, v: u64) {
        self.0
            .get_mut(97..105)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(&v.to_le_bytes());
    }

    #[inline]
    fn set_exit_epoch(&mut self, v: u64) {
        self.0
            .get_mut(105..113)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(&v.to_le_bytes());
    }

    #[inline]
    fn set_withdrawable_epoch(&mut self, v: u64) {
        self.0
            .get_mut(113..121)
            .expect("ByteValidatorMut contains a complete SSZ validator record")
            .copy_from_slice(&v.to_le_bytes());
    }
}

/// Collection wrapper implementing `ValidatorMutTarget` for `Vec<u8>`.
struct ByteValidatorTarget<'a>(&'a mut Vec<u8>);

impl<'a> ValidatorMutTarget for ByteValidatorTarget<'a> {
    type Validator<'b>
        = ByteValidatorMut<'b>
    where
        Self: 'b;

    fn get_mut(&mut self, index: usize) -> Option<Self::Validator<'_>> {
        let start = index.checked_mul(VALIDATOR_SSZ_SIZE)?;
        let end = start.checked_add(VALIDATOR_SSZ_SIZE)?;
        self.0.get_mut(start..end).map(ByteValidatorMut)
    }

    fn push_from_ssz(&mut self, ssz_bytes: &[u8]) {
        self.0.extend_from_slice(ssz_bytes);
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::{ArchivedValidatorsDiff, ValidatorField};

    fn archive(diff: &ValidatorsDiff) -> rkyv::util::AlignedVec {
        rkyv::to_bytes::<rkyv::rancor::Error>(diff).expect("test setup: failed to serialize delta")
    }

    fn archived(bytes: &[u8]) -> &ArchivedValidatorsDiff {
        rkyv::access::<ArchivedValidatorsDiff, rkyv::rancor::Error>(bytes)
            .expect("test setup: failed to access archived delta")
    }

    #[derive(Clone, Debug, PartialEq, Eq)]
    struct MockValidator {
        withdrawal_credentials: [u8; 32],
        effective_balance: u64,
        slashed: bool,
        activation_eligibility_epoch: u64,
        activation_epoch: u64,
        exit_epoch: u64,
        withdrawable_epoch: u64,
    }

    impl MockValidator {
        fn new(id: u8) -> Self {
            Self {
                withdrawal_credentials: [id; 32],
                effective_balance: 32_000_000_000,
                slashed: false,
                activation_eligibility_epoch: 0,
                activation_epoch: 0,
                exit_epoch: 0,
                withdrawable_epoch: 0,
            }
        }

        /// Serializes to the exact canonical SSZ layout expected by ByteValidator.
        fn to_ssz_bytes(&self) -> Vec<u8> {
            let mut bytes = vec![0u8; VALIDATOR_SSZ_SIZE];
            bytes[48..80].copy_from_slice(&self.withdrawal_credentials);
            bytes[80..88].copy_from_slice(&self.effective_balance.to_le_bytes());
            bytes[88] = self.slashed as u8;
            bytes[89..97].copy_from_slice(&self.activation_eligibility_epoch.to_le_bytes());
            bytes[97..105].copy_from_slice(&self.activation_epoch.to_le_bytes());
            bytes[105..113].copy_from_slice(&self.exit_epoch.to_le_bytes());
            bytes[113..121].copy_from_slice(&self.withdrawable_epoch.to_le_bytes());
            bytes
        }
    }

    impl ValidatorSnapshot for MockValidator {
        fn withdrawal_credentials(&self) -> &[u8; 32] {
            &self.withdrawal_credentials
        }
        fn effective_balance(&self) -> u64 {
            self.effective_balance
        }
        fn is_slashed(&self) -> bool {
            self.slashed
        }
        fn activation_eligibility_epoch(&self) -> u64 {
            self.activation_eligibility_epoch
        }
        fn activation_epoch(&self) -> u64 {
            self.activation_epoch
        }
        fn exit_epoch(&self) -> u64 {
            self.exit_epoch
        }
        fn withdrawable_epoch(&self) -> u64 {
            self.withdrawable_epoch
        }
        fn to_ssz_bytes(&self) -> Vec<u8> {
            self.to_ssz_bytes()
        }
    }

    /// Mock mutable wrapper for the apply API.
    struct MockMutValidator<'a>(&'a mut MockValidator);

    impl<'a> ValidatorMut for MockMutValidator<'a> {
        fn is_slashed(&self) -> bool {
            self.0.slashed
        }
        fn set_withdrawal_credentials(&mut self, v: &[u8; 32]) {
            self.0.withdrawal_credentials = *v;
        }
        fn set_effective_balance(&mut self, v: u64) {
            self.0.effective_balance = v;
        }
        fn set_slashed(&mut self, v: bool) {
            self.0.slashed = v;
        }
        fn set_activation_eligibility_epoch(&mut self, v: u64) {
            self.0.activation_eligibility_epoch = v;
        }
        fn set_activation_epoch(&mut self, v: u64) {
            self.0.activation_epoch = v;
        }
        fn set_exit_epoch(&mut self, v: u64) {
            self.0.exit_epoch = v;
        }
        fn set_withdrawable_epoch(&mut self, v: u64) {
            self.0.withdrawable_epoch = v;
        }
    }

    /// Mock collection target for the apply API.
    struct MockValidatorTarget {
        validators: Vec<MockValidator>,
    }

    impl ValidatorMutTarget for MockValidatorTarget {
        type Validator<'a>
            = MockMutValidator<'a>
        where
            Self: 'a;

        fn get_mut(&mut self, index: usize) -> Option<Self::Validator<'_>> {
            self.validators.get_mut(index).map(MockMutValidator)
        }

        fn push_from_ssz(&mut self, ssz_bytes: &[u8]) {
            // In production, apply_validators_iter guarantees chunks_exact(VALIDATOR_SSZ_SIZE)
            let wc = ssz_bytes
                .get(48..80)
                .and_then(|s| s.try_into().ok())
                .expect("test setup: valid wc bytes");
            let eb = u64::from_le_bytes(
                ssz_bytes
                    .get(80..88)
                    .and_then(|s| s.try_into().ok())
                    .expect("test setup: valid eb bytes"),
            );
            let slashed = ssz_bytes.get(88).copied().expect("test setup") != 0;
            let aee = u64::from_le_bytes(
                ssz_bytes
                    .get(89..97)
                    .and_then(|s| s.try_into().ok())
                    .expect("test setup: valid aee bytes"),
            );
            let ae = u64::from_le_bytes(
                ssz_bytes
                    .get(97..105)
                    .and_then(|s| s.try_into().ok())
                    .expect("test setup: valid ae bytes"),
            );
            let ee = u64::from_le_bytes(
                ssz_bytes
                    .get(105..113)
                    .and_then(|s| s.try_into().ok())
                    .expect("test setup: valid ee bytes"),
            );
            let we = u64::from_le_bytes(
                ssz_bytes
                    .get(113..121)
                    .and_then(|s| s.try_into().ok())
                    .expect("test setup: valid we bytes"),
            );

            self.validators.push(MockValidator {
                withdrawal_credentials: wc,
                effective_balance: eb,
                slashed,
                activation_eligibility_epoch: aee,
                activation_epoch: ae,
                exit_epoch: ee,
                withdrawable_epoch: we,
            });
        }
    }

    #[test]
    fn test_no_changes_iter() {
        let base = vec![MockValidator::new(0), MockValidator::new(1)];
        let target = base.clone();
        let delta = diff_validators_iter(base.into_iter(), target.into_iter());
        assert_eq!(delta.patches.len(), 0);
        assert_eq!(delta.appended_validators.len(), 0);
    }

    #[test]
    fn test_single_field_change_iter() {
        let base = vec![MockValidator::new(0)];
        let mut target = vec![MockValidator::new(0)];
        target[0].effective_balance = 31_000_000_000;

        let delta = diff_validators_iter(base.clone().into_iter(), target.clone().into_iter());
        assert_eq!(delta.patches.len(), 1);
        assert_eq!(delta.patches[0].field, ValidatorField::EffectiveBalance);
    }

    #[test]
    fn test_appended_validators_iter() {
        let base = vec![MockValidator::new(0)];
        let target = vec![MockValidator::new(0), MockValidator::new(1)];

        let delta = diff_validators_iter(base.into_iter(), target.into_iter());
        assert_eq!(delta.patches.len(), 0);
        assert_eq!(delta.appended_validators.len(), VALIDATOR_SSZ_SIZE);
    }

    #[test]
    fn test_withdrawable_epoch_auto_reconstructed_non_slashed() {
        let base = MockValidator::new(0);
        let mut target = base.clone();

        target.exit_epoch = 100;
        target.withdrawable_epoch = 100 + MIN_VALIDATOR_WITHDRAWABILITY_DELAY;

        let delta = diff_validators_iter(
            std::iter::once(base.clone()),
            std::iter::once(target.clone()),
        );

        // Should ONLY patch exit_epoch. Withdrawable epoch is derived.
        assert_eq!(delta.patches.len(), 1);
        assert_eq!(delta.patches[0].field, ValidatorField::ExitEpoch);

        let bytes = archive(&delta);
        let archived = archived(&bytes);

        let mut state = MockValidatorTarget {
            validators: vec![base],
        };
        apply_validators_iter(&mut state, archived).expect("test setup: apply failed");

        assert_eq!(state.validators[0], target);
    }

    #[test]
    fn test_withdrawable_epoch_explicit_patch_slashed() {
        let mut base = MockValidator::new(0);
        base.slashed = true;

        let mut target = base.clone();
        target.exit_epoch = 100;
        target.withdrawable_epoch = 150; // Slashed can have early withdrawal

        let delta = diff_validators_iter(
            std::iter::once(base.clone()),
            std::iter::once(target.clone()),
        );

        // MUST patch BOTH exit_epoch and withdrawable_epoch for slashed validators
        assert_eq!(delta.patches.len(), 2);
        let fields: Vec<&ValidatorField> = delta.patches.iter().map(|p| &p.field).collect();
        assert!(fields.contains(&&ValidatorField::ExitEpoch));
        assert!(fields.contains(&&ValidatorField::WithdrawableEpochSlashed));

        let bytes = archive(&delta);
        let archived = archived(&bytes);

        let mut state = MockValidatorTarget {
            validators: vec![base],
        };
        apply_validators_iter(&mut state, archived).expect("test setup: apply failed");

        assert_eq!(state.validators[0], target);
    }

    #[test]
    fn test_byte_api_roundtrip() {
        let base = [MockValidator::new(0), MockValidator::new(1)];
        let target = [MockValidator::new(0), MockValidator::new(2)];

        let base_bytes: Vec<u8> = base.iter().flat_map(|v| v.to_ssz_bytes()).collect();
        let target_bytes: Vec<u8> = target.iter().flat_map(|v| v.to_ssz_bytes()).collect();

        let delta = diff_validators(&base_bytes, &target_bytes);

        let bytes = archive(&delta);
        let archived = archived(&bytes);

        let mut reconstructed = base_bytes;
        apply_validators(&mut reconstructed, archived).expect("test setup: apply failed");

        assert_eq!(reconstructed, target_bytes);
    }

    #[test]
    fn test_apply_out_of_bounds_index() {
        let base = vec![MockValidator::new(0)];
        let mut target = vec![MockValidator::new(0)];
        target[0].effective_balance = 100;

        let delta = diff_validators_iter(base.into_iter(), target.into_iter());
        let bytes = archive(&delta);
        let archived = archived(&bytes);

        // Try applying to an empty collection
        let mut state = MockValidatorTarget { validators: vec![] };

        let result = apply_validators_iter(&mut state, archived);
        assert!(result.is_err());
        let err_str = format!("{}", result.expect_err("test setup"));
        assert!(err_str.contains("out of bounds"));
    }

    #[test]
    fn test_apply_invalid_patch_width() {
        // Construct a delta with an explicitly invalid patch width natively
        let delta = ValidatorsDiff {
            patches: vec![ValidatorPatch {
                index: 0,
                field: ValidatorField::EffectiveBalance, // Expects 8 bytes
                value: vec![0; 4],                       // Invalid! Only 4 bytes
            }],
            appended_validators: vec![],
        };

        let bytes = archive(&delta);
        let archived = archived(&bytes);

        let mut state = MockValidatorTarget {
            validators: vec![MockValidator::new(0)],
        };

        let result = apply_validators_iter(&mut state, archived);
        assert!(result.is_err());
        let err_str = format!("{}", result.expect_err("test setup"));
        assert!(
            err_str.contains("expected 8 bytes, got 4"),
            "Error message should mention invalid width"
        );
    }

    #[test]
    fn test_apply_truncated_appended_validators() {
        // Construct a delta where the appended validators length is not a multiple of SSZ size
        let delta = ValidatorsDiff {
            patches: vec![],
            appended_validators: vec![0u8; VALIDATOR_SSZ_SIZE - 1], // 1 byte short of a full record
        };

        let bytes = archive(&delta);
        let archived = archived(&bytes);

        let mut state = MockValidatorTarget { validators: vec![] };

        let result = apply_validators_iter(&mut state, archived);
        assert!(result.is_err());
        let err_str = format!("{}", result.expect_err("test setup"));
        assert!(
            err_str.contains("does not contain complete SSZ records"),
            "Error message should mention truncated appended data"
        );
    }
}