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
//! Delta encoding for SSZ lists that behave as FIFO queues.
//!
//! This module computes compact deltas between serialized SSZ queues by
//! identifying items that have been consumed from the front of the queue and
//! items that have been appended to the back.
//!
//! The encoding supports two representations:
//!
//! - [`QueueDiff::Fifo`] records the number of items consumed from the front
//! and the serialized items appended to the back.
//! - [`QueueDiff::FullReplacement`] stores the complete target queue when the
//! FIFO relationship cannot be established safely.
//!
//! The FIFO representation is suitable for consensus-layer queues whose
//! logical behavior is append-at-the-back and consume-from-the-front, such as
//! pending withdrawals and consolidations. It also supports queues such as
//! pending deposits where reordering may occur: when the FIFO relationship
//! cannot be proven from the serialized representation, the algorithm falls
//! back to [`QueueDiff::FullReplacement`] rather than producing an unsafe
//! delta.
//!
//! ## Candidate detection and validation
//!
//! To identify a candidate overlap, the encoder searches for the first item of
//! the target queue within the base queue. Matching is performed only at valid
//! SSZ item boundaries determined by `item_ssz_size`.
//!
//! Finding an item alone is not sufficient to establish a FIFO transition.
//! After a candidate overlap is found, the encoder verifies that the remaining
//! bytes of the base queue exactly match the corresponding prefix of the target
//! queue. Only after this validation succeeds is a [`QueueDiff::Fifo`] emitted.
//!
//! If no valid overlap is found, or the remaining queue contents do not match,
//! the encoder emits [`QueueDiff::FullReplacement`] containing the complete
//! target queue.
//!
//! This conservative fallback ensures that an ambiguous or reordered queue
//! is never represented as an incorrect FIFO delta.
//!
//! ## Representation
//!
//! For a valid FIFO transition:
//!
//! ```text
//! base: [A, B, C, D]
//! target: [C, D, E, F]
//! ^--- appended
//!
//! consumed_count = 2
//! appended_items = [E, F]
//! ```
//!
//! Applying the delta removes `A` and `B`, then appends `E` and `F`.
//!
//! ## Requirements
//!
//! `item_ssz_size` must be the fixed serialized SSZ size of one queue item
//! and must be greater than zero. The input buffers must contain complete
//! items, so their lengths must be exact multiples of `item_ssz_size`.
//!
//! The module operates directly on serialized SSZ bytes and does not require
//! deserializing individual queue items during diff generation.
//!
//! ## Complexity
//!
//! [`diff_queue`] performs a linear scan of the base queue for the target head,
//! followed by a linear validation of the candidate overlap. The resulting
//! algorithm is O(n) in the size of the serialized queues.
//!
//! [`apply_queue`] performs O(n) work proportional to the bytes consumed and
//! appended for a FIFO delta, or O(n) in the target queue size for a full
//! replacement.
//!
//! # Example
//!
//! ```
//! # use eth_state_diff::types::QueueDiff;
//! # use eth_state_diff::pending_queue::diff_queue;
//!
//! const ITEM_SIZE: usize = 4;
//!
//! let base = b"AAAABBBBCCCC";
//! let target = b"CCCCDDDDEEEE";
//!
//! let delta = diff_queue(base, target, ITEM_SIZE);
//!
//! assert_eq!(
//! delta,
//! QueueDiff::Fifo {
//! consumed_count: 2,
//! appended_items: b"DDDDEEEE".to_vec(),
//! }
//! );
//! ```
use crate::;
/// Finds the first occurrence of an SSZ-encoded queue item within `haystack`,
/// considering only valid item boundaries.
///
/// The search is performed in `item_ssz_size`-byte chunks rather than with a
/// byte-level substring search. This prevents a sequence of bytes occurring
/// inside one SSZ item from being incorrectly interpreted as a queue-item
/// boundary.
///
/// Returns the byte offset of the first matching item, or `None` if no aligned
/// match exists.
///
/// # Requirements
///
/// `needle.len()` must equal `item_ssz_size`. If it does not, the function
/// returns `None`.
/// Computes a delta between two serialized SSZ queues.
///
/// The encoder first attempts to represent the transition as a FIFO operation:
///
/// 1. The first item of `target_ssz` is located in `base_ssz`.
/// 2. The search is restricted to valid item boundaries using
/// `item_ssz_size`.
/// 3. The remaining bytes of the base queue are compared with the corresponding
/// prefix of the target queue.
/// 4. If they match exactly, the transition is represented as
/// [`QueueDiff::Fifo`].
/// 5. Otherwise, the complete target queue is stored as
/// [`QueueDiff::FullReplacement`].
///
/// This validation is important for queues that may occasionally reorder
/// items. An overlap by itself does not prove that the target is a continuation
/// of the base queue.
///
/// # Arguments
///
/// * `base_ssz` - Serialized SSZ representation of the base queue.
/// * `target_ssz` - Serialized SSZ representation of the target queue.
/// * `item_ssz_size` - Fixed serialized SSZ size, in bytes, of one queue item.
///
/// # Returns
///
/// [`QueueDiff::Fifo`] when the target can be safely represented as consumed
/// items followed by appended items. Otherwise returns
/// [`QueueDiff::FullReplacement`] containing the complete target queue.
///
/// # Panics
///
/// Panics if `item_ssz_size` is zero or if either input contains an incomplete
/// serialized item.
///
/// # Complexity
///
/// O(n) time, where *n* is the combined size of the queues in bytes, with
/// O(m) additional space for the encoded appended or replacement bytes.
///
/// # Example
///
/// ```
/// # use eth_state_diff::pending_queue::diff_queue;
/// # use eth_state_diff::types::QueueDiff;
///
/// const ITEM_SIZE: usize = 4;
///
/// let base = b"AAAABBBBCCCC";
/// let target = b"CCCCDDDDEEEE";
///
/// let delta = diff_queue(base, target, ITEM_SIZE);
///
/// assert_eq!(
/// delta,
/// QueueDiff::Fifo {
/// consumed_count: 2,
/// appended_items: b"DDDDEEEE".to_vec(),
/// }
/// );
/// ```
/// Applies a queue delta to a serialized SSZ queue in place.
///
/// For [`QueueDiff::Fifo`], the specified number of items are removed from the
/// front of `base`, after which the appended serialized items are added to the
/// back.
///
/// For [`QueueDiff::FullReplacement`], the existing queue is cleared and
/// replaced with the serialized target queue stored in the delta.
///
/// # Arguments
///
/// * `base` - Mutable serialized SSZ representation of the queue to update.
/// * `delta` - Archived queue delta previously produced by [`diff_queue`] and
/// serialized with `rkyv`.
/// * `item_ssz_size` - Fixed serialized SSZ size of one queue item.
///
/// # Errors
///
/// Returns [`Error::MalformedDelta`] if:
///
/// - the archived delta cannot be deserialized;
/// - `item_ssz_size` is inconsistent with the serialized delta;
/// - the number of consumed items exceeds the number of items in `base`;
/// - the consumed-byte calculation overflows;
/// - appended or replacement bytes are not aligned to `item_ssz_size`.
///
/// # Behavior
///
/// After successful execution, `base` represents the target queue from which
/// the delta was originally generated.
///
/// # Complexity
///
/// For [`QueueDiff::Fifo`], the operation is O(n) in the number of bytes
/// removed and appended. Removing bytes from the front may require shifting
/// the remaining contents of the `Vec`.
///
/// For [`QueueDiff::FullReplacement`], the operation is O(n) in the size of
/// the replacement queue.
///
/// # Example
///
/// ```
/// # use eth_state_diff::pending_queue::{apply_queue, diff_queue};
///
/// const ITEM_SIZE: usize = 4;
///
/// let mut base = b"AAAABBBBCCCC".to_vec();
/// let target = b"CCCCDDDDEEEE";
///
/// let delta = diff_queue(&base, target, ITEM_SIZE);
/// let bytes = rkyv::to_bytes::<rkyv::rancor::Error>(&delta).unwrap();
/// let archived = unsafe {
/// rkyv::access_unchecked::<eth_state_diff::types::ArchivedQueueDiff>(&bytes)
/// };
///
/// apply_queue(&mut base, archived, ITEM_SIZE).unwrap();
///
/// assert_eq!(base, target);
/// ```