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
//! Core data structures used by [`eth_state_diff`].
//!
//! This module defines the serialized delta representations produced by the
//! crate's diff algorithms.
//!
//! The structures in this module are deliberately independent of any specific
//! Ethereum consensus-client implementation. They contain only primitive Rust
//! values, byte buffers, and `rkyv`-archivable types. This allows a delta to be:
//!
//! 1. computed from one consensus state and another;
//! 2. serialized with [`rkyv`];
//! 3. optionally compressed with a general-purpose compressor such as zstd;
//! 4. stored as an archival record; and
//! 5. later deserialized and applied to another compatible state.
//!
//! # Delta model
//!
//! Most types in this module represent the transformation:
//!
//! ```text
//! base state + delta -> target state
//! ```
//!
//! Different consensus-state fields have different update patterns, so the
//! crate uses specialized representations rather than one universal encoding.
//! For example:
//!
//! - validator registries use field-level patches;
//! - balances use packed tags and varint-encoded differences;
//! - participation and inactivity scores use sparse updates;
//! - FIFO-like lists use consumed-item counts and appended bytes;
//! - circular buffers store only values written during the transition;
//! - append-only historical logs use protocol-defined append counts; and
//! - fields that change infrequently use unchanged/full-replacement variants.
//!
//! # Serialization
//!
//! All public delta structures derive [`rkyv::Archive`], [`rkyv::Serialize`],
//! and [`rkyv::Deserialize`]. They are therefore suitable for use as the
//! serialized representation of an archival state delta.
//!
//! The structures themselves do not perform compression. Applications can
//! serialize a delta with `rkyv` and subsequently compress the resulting bytes
//! using a compressor such as zstd.
//!
//! # Compatibility
//!
//! The delta types describe the encoding used by this crate. They should be
//! treated as part of the crate's serialization format: changing field types,
//! enum variants, or encoding invariants may affect the compatibility of
//! previously stored deltas.
//!
//! [`eth_state_diff`]: crate
use ;
/// Number of slots in an Ethereum consensus epoch.
///
/// Ethereum mainnet uses 32 slots per epoch.
pub const SLOTS_PER_EPOCH: u64 = 32;
/// Size, in bytes, of an SSZ-serialized `Validator` record.
///
/// The size corresponds to the Phase0 validator container represented by this
/// crate. Validator records are treated as fixed-width byte sequences by the
/// byte-oriented validator diff implementation.
pub const VALIDATOR_SSZ_SIZE: usize = 121;
/// Size, in bytes, of an SSZ-serialized historical root.
///
/// A root is a 32-byte hash.
pub const HISTORICAL_ROOTS_SSZ_SIZE: usize = 32;
/// Size, in bytes, of an SSZ-serialized historical summary.
///
/// Historical summaries represented by this crate occupy 64 bytes.
pub const HISTORICAL_SUMMARIES_SSZ_SIZE: usize = 64;
/// Minimum validator withdrawability delay used when reconstructing the
/// `withdrawable_epoch` of a non-slashed validator.
///
/// When a validator is not slashed, its withdrawable epoch can be derived from
/// its exit epoch and this protocol-defined delay rather than being stored as
/// an independent delta field.
pub const MIN_VALIDATOR_WITHDRAWABILITY_DELAY: u64 = 256;
/// Identifies a validator field modified by a [`ValidatorPatch`].
///
/// Validator fields are encoded independently so that changing one field does
/// not require storing the complete 121-byte validator SSZ record.
///
/// The `WithdrawableEpochSlashed` variant is used specifically for slashed
/// validators. For non-slashed validators, `withdrawable_epoch` is derived
/// deterministically from `exit_epoch` and
/// [`MIN_VALIDATOR_WITHDRAWABILITY_DELAY`].
/// A modification to a single validator field.
///
/// Each patch identifies the validator by its registry index and contains the
/// replacement value for exactly one [`ValidatorField`].
///
/// The `value` field contains the encoded representation expected by the
/// corresponding field. The interpretation depends on [`ValidatorField`].
///
/// For example:
///
/// - `WithdrawalCredentials` contains 32 bytes;
/// - integer epoch and balance fields contain their little-endian `u64`
/// representation; and
/// - `Slashed` contains a single byte.
///
/// This structure is intended to be produced by the validator diff algorithm
/// rather than constructed manually.
/// Compact representation of the difference between two validator registries.
///
/// Existing validators are represented using field-level [`ValidatorPatch`]es.
/// Validators present only in the target registry are stored as consecutive
/// raw SSZ validator records in [`Self::appended_validators`].
///
/// This avoids rewriting complete validator records when only a small number
/// of fields changed.
///
/// # Reconstruction
///
/// Applying all patches to the common validator range and then appending the
/// records in `appended_validators` reconstructs the target registry.
/// Compact representation of the difference between two validator balance
/// snapshots.
///
/// The representation combines four mechanisms:
///
/// - [`BitTagVec`] stores a two-bit operation for each balance;
/// - `mode` stores the most common representable balance difference;
/// - `varint_payload` stores mode-adjusted signed differences using
/// zig-zag encoding; and
/// - `target_values` stores balances that are more efficiently represented as
/// absolute values.
///
/// Validators that exist only in the target snapshot are stored in
/// `appended_balances`.
///
/// This representation is designed to serialize efficiently with `rkyv` and
/// compress well with general-purpose compressors such as zstd.
///
/// # Reconstruction
///
/// Each tag determines how the corresponding target balance is reconstructed:
///
/// - unchanged balances require no payload;
/// - zero balances are set directly to zero;
/// - difference-encoded balances are reconstructed from `mode` and the
/// corresponding varint; and
/// - absolute values are read from `target_values`.
/// Compact delta representation for Ethereum participation flags.
///
/// The encoder selects between a dense all-zero representation and a sparse
/// representation depending on the target vector.
///
/// This type is intended to be serialized using `rkyv`.
/// Compact delta representation for validator inactivity scores.
///
/// The encoder uses a dedicated all-zero representation when the target vector
/// contains only zero scores. Otherwise, only changed scores are stored.
///
/// Scores belonging to validators appended to the target vector are stored
/// separately in `extensions`.
/// Sequence of roots written while advancing through a circular root buffer.
///
/// Roots are stored in chronological slot order. The slot used to reconstruct
/// the first entry is supplied separately to the apply function.
///
/// The buffer capacity is intentionally not serialized into the delta because
/// it is already known by the destination state.
/// Sparse updates for an Ethereum slashing ring buffer.
///
/// Each update identifies a ring-buffer index and the replacement slashing
/// total for that index.
///
/// Entries that do not appear in this vector are left unchanged during
/// application.
/// Sequence of RANDAO mixes written while advancing through epochs.
///
/// Mixes are stored in chronological epoch order. The destination ring-buffer
/// capacity is supplied separately during application.
///
/// The capacity is intentionally omitted from the serialized representation
/// because it is a property of the destination consensus state.
/// Delta representation for an Ethereum Eth1 data vote list.
///
/// The list normally grows by appending votes within an Eth1 voting period.
/// When the voting period resets, the representation switches to
/// [`Eth1DataVotesDiff::ResetAndAppend`].
/// Universal delta representation for SSZ-serialized queue-like lists.
///
/// The representation supports both:
///
/// - FIFO transitions, where items are consumed from the front and appended at
/// the back; and
/// - safe fallback to complete replacement when the FIFO assumptions cannot be
/// established.
///
/// The FIFO representation stores raw SSZ bytes rather than deserializing
/// individual queue items.
/// Delta representation for an Ethereum sync committee.
///
/// Sync committees are stable for a sync committee period. Consequently, most
/// state-diff windows can represent the committee using
/// [`SyncCommitteeDiff::Unchanged`].
///
/// When the committee changes, the complete serialized target committee is
/// stored as a replacement rather than attempting to encode individual member
/// changes.
/// Delta representation for an append-only historical consensus log.
///
/// Historical roots and historical summaries are appended according to
/// protocol-defined slot intervals. The diff algorithm can therefore determine
/// how many entries should have been appended from the slot transition rather
/// than comparing the complete base and target buffers.
/// Delta representation for Phase0 pending attestation lists.
///
/// The representation supports both append-only transitions and complete
/// replacement. This matches the two update patterns used by
/// `current_epoch_attestations` and `previous_epoch_attestations`.
/// Packed two-bit operation tags used by [`BalancesDiff`].
///
/// Four tags are stored in each byte, with the tag for index `i` occupying
/// bits `((i % 4) * 2)..((i % 4) * 2 + 2)`.
///
/// The four tag values are:
///
/// | Tag | Meaning |
/// | --- | --- |
/// | `00` | Balance is unchanged |
/// | `01` | Replace with an absolute target value |
/// | `10` | Set balance to zero |
/// | `11` | Apply an encoded balance difference |
///
/// A newly created [`BitTagVec`] is initialized entirely with
/// [`SET_NO_CHANGE`] tags.
///
/// # Storage
///
/// A vector containing *n* logical tags requires:
///
/// ```text
/// ceil(n / 4)
/// ```
///
/// bytes of backing storage.
///
/// # Example
///
/// ```
/// use eth_state_diff::types::{BitTagVec, SET_TO_DIFF, SET_TO_ZERO};
///
/// let mut tags = BitTagVec::new(6);
///
/// tags.set(0, SET_TO_DIFF);
/// tags.set(4, SET_TO_ZERO);
///
/// assert_eq!(tags.get(0), SET_TO_DIFF);
/// assert_eq!(tags.get(1), 0);
/// assert_eq!(tags.get(4), SET_TO_ZERO);
/// ```
/// Tag indicating that the corresponding balance is unchanged.
pub const SET_NO_CHANGE: u8 = 0b00;
/// Tag indicating that the corresponding balance is replaced with zero.
pub const SET_TO_ZERO: u8 = 0b10;
/// Tag indicating that the corresponding balance is reconstructed by applying
/// an encoded signed difference.
pub const SET_TO_DIFF: u8 = 0b11;
/// Tag indicating that the corresponding balance is replaced with an absolute
/// target value.
pub const SET_TO_TARGET_VALUE: u8 = 0b01;