zakura-network 1.0.0

Networking code for the Zakura node. Internal crate, published to support cargo install zakura
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
use super::{error::*, events::*, scheduler::*, validation::*, wire::*, *};
use crate::zakura::{
    HeaderSyncServiceSummary, ServicePeerDirection, DEFAULT_LIVE_SERVICE_SUMMARY_TTL,
};

pub(super) const HEADER_SYNC_ADVISORY_BACKOFF_FAILURES: u32 = 2;
pub(super) const HEADER_SYNC_ADVISORY_BACKOFF: Duration = Duration::from_secs(60);
pub(super) const HEADER_SYNC_ADVISORY_TTL: Duration = DEFAULT_LIVE_SERVICE_SUMMARY_TTL;
pub(super) const HEADER_SYNC_STALE_ANCHOR_LINK_FAILURES: u32 = 3;
pub(super) const HEADER_SYNC_STALE_ANCHOR_DISTINCT_PEERS: usize = 2;
pub(super) const VCT_ROOT_REPAIR_MAX_ATTEMPTS: usize = 6;
pub(super) const VCT_ROOT_REPAIR_MAX_WALL_TIME: Duration = Duration::from_secs(240);
pub(super) const VCT_ROOT_REPAIR_BACKOFFS: [Duration; VCT_ROOT_REPAIR_MAX_ATTEMPTS] = [
    Duration::from_secs(0),
    Duration::from_secs(1),
    Duration::from_secs(2),
    Duration::from_secs(4),
    Duration::from_secs(8),
    Duration::from_secs(16),
];

#[derive(Clone, Debug)]
pub(super) struct HeaderSyncCore {
    pub(super) anchor: (block::Height, block::Hash),
    pub(super) finalized_height: block::Height,
    pub(super) verified_block_tip: block::Height,
    pub(super) verified_block_hash: block::Hash,
    pub(super) best_header_tip: block::Height,
    pub(super) best_header_hash: block::Hash,
    pub(super) peers: HashMap<ZakuraPeerId, PeerHeaderState>,
    pub(super) parked_peers: HashSet<ZakuraPeerId>,
    pub(super) seen: HeaderHashDedup,
    pub(super) pending_new_blocks: HashSet<block::Hash>,
    pub(super) schedule: RangeScheduler,
    pub(super) pending_commits: HashMap<PendingCommitKey, RangeRequest>,
    pub(super) repair: Option<VctRootRepair>,
    pub(super) advisory: HashMap<ZakuraPeerId, HeaderSyncAdvisoryPeerState>,
    pub(super) stale_anchor: StaleAnchorFailures,
}

impl HeaderSyncCore {
    pub(super) fn new(startup: &HeaderSyncStartup) -> Result<Self, HeaderSyncStartError> {
        validate_anchor(&startup.network, startup.anchor)?;
        let (best_header_tip, best_header_hash) = startup.best_header_tip.unwrap_or(startup.anchor);

        Ok(Self {
            anchor: startup.anchor,
            finalized_height: startup.frontiers.finalized_height,
            verified_block_tip: startup.frontiers.verified_block_tip,
            verified_block_hash: startup.frontiers.verified_block_hash,
            best_header_tip,
            best_header_hash,
            peers: HashMap::new(),
            parked_peers: HashSet::new(),
            seen: HeaderHashDedup::default(),
            pending_new_blocks: HashSet::new(),
            schedule: RangeScheduler::new(),
            pending_commits: HashMap::new(),
            repair: None,
            advisory: HashMap::new(),
            stale_anchor: StaleAnchorFailures::default(),
        })
    }

    pub(super) fn refresh_forward_range(&mut self, startup: &HeaderSyncStartup) {
        let best_peer_tip = self
            .peers
            .values()
            .filter(|peer| peer.received_status)
            .map(|peer| peer.advertised_tip)
            .max()
            .unwrap_or(self.best_header_tip);
        if best_peer_tip <= self.best_header_tip {
            return;
        }

        let checkpoints = startup.network.checkpoint_list();
        let Some(start) = next_height(self.best_header_tip) else {
            return;
        };
        let mut end = best_peer_tip;
        let mut finalized = false;
        if let Some(first_checkpoint) = checkpoints.min_height_in_range(block::Height(1)..) {
            if self.best_header_tip < first_checkpoint {
                if best_peer_tip < first_checkpoint {
                    return;
                }
                end = first_checkpoint;
                finalized = true;
            }
        }

        let count = count_between(start, end);
        if count == 0 {
            return;
        }
        self.schedule.ensure_forward(RangeRequest {
            start_height: start,
            count,
            anchor_hash: self.best_header_hash,
            finalized,
            want_tree_aux_roots: true,
            priority: RangePriority::Forward,
        });
    }

    pub(super) fn refresh_backward_range(&mut self, startup: &HeaderSyncStartup) {
        if self.anchor.0 == block::Height(0) {
            return;
        }
        let checkpoints = startup.network.checkpoint_list();
        // v1 backfill schedules one checkpoint bracket below the configured anchor.
        // Iterating all deeper brackets is left to final node wiring/backfill policy.
        let Some(previous_checkpoint) = checkpoints.max_height_in_range(..self.anchor.0) else {
            return;
        };
        let Some(previous_hash) = checkpoints.hash(previous_checkpoint) else {
            return;
        };
        let Some(start) = next_height(previous_checkpoint) else {
            return;
        };
        let count = count_between(start, self.anchor.0);
        if count == 0 {
            return;
        }
        self.schedule.ensure_backward(RangeRequest {
            start_height: start,
            count,
            anchor_hash: previous_hash,
            finalized: true,
            want_tree_aux_roots: true,
            priority: RangePriority::Backward,
        });
    }
}

#[derive(Clone, Debug)]
pub(super) struct VctRootRepair {
    pub(super) height: block::Height,
    pub(super) generation: u64,
    pub(super) range: RangeRequest,
    pub(super) expected_hashes: Vec<(block::Height, block::Hash)>,
    pub(super) tried_peers: HashSet<ZakuraPeerId>,
    pub(super) in_flight: Option<ZakuraPeerId>,
    pub(super) started_at: Instant,
    pub(super) next_attempt_at: Instant,
    pub(super) exhausted: bool,
}

impl VctRootRepair {
    pub(super) fn new(
        height: block::Height,
        generation: u64,
        anchor_hash: block::Hash,
        expected_hashes: Vec<(block::Height, block::Hash)>,
    ) -> Option<Self> {
        let count = u32::try_from(expected_hashes.len()).ok()?;
        if count == 0 || count > 2 {
            return None;
        }
        let first_height = expected_hashes.first()?.0;
        if first_height != height {
            return None;
        }
        if !expected_hashes
            .iter()
            .enumerate()
            .all(|(index, (candidate_height, _))| {
                u32::try_from(index)
                    .ok()
                    .and_then(|offset| height.0.checked_add(offset))
                    .map(block::Height)
                    == Some(*candidate_height)
            })
        {
            return None;
        }

        Some(Self {
            height,
            generation,
            range: RangeRequest {
                start_height: height,
                count,
                anchor_hash,
                finalized: false,
                want_tree_aux_roots: true,
                priority: RangePriority::Repair,
            },
            expected_hashes,
            tried_peers: HashSet::new(),
            in_flight: None,
            started_at: Instant::now(),
            next_attempt_at: Instant::now(),
            exhausted: false,
        })
    }

    pub(super) fn can_attempt(&self, now: Instant) -> bool {
        !self.exhausted
            && self.in_flight.is_none()
            && self.tried_peers.len() < VCT_ROOT_REPAIR_MAX_ATTEMPTS
            && now.duration_since(self.started_at) < VCT_ROOT_REPAIR_MAX_WALL_TIME
            && now >= self.next_attempt_at
    }

    pub(super) fn mark_attempt(&mut self, peer: ZakuraPeerId) {
        self.tried_peers.insert(peer.clone());
        self.in_flight = Some(peer);
    }

    pub(super) fn finish_attempt(&mut self, peer: &ZakuraPeerId, now: Instant) -> bool {
        if self.in_flight.as_ref() != Some(peer) {
            return false;
        }
        self.in_flight = None;
        let attempt_index = self
            .tried_peers
            .len()
            .saturating_sub(1)
            .min(VCT_ROOT_REPAIR_MAX_ATTEMPTS - 1);
        self.next_attempt_at = now + VCT_ROOT_REPAIR_BACKOFFS[attempt_index];
        self.refresh_exhausted(now);
        true
    }

    /// Marks an episode exhausted once either bound has elapsed.
    ///
    /// Returns `true` only for the transition so callers emit operator signals once.
    pub(super) fn refresh_exhausted(&mut self, now: Instant) -> bool {
        if self.exhausted
            || (self.tried_peers.len() < VCT_ROOT_REPAIR_MAX_ATTEMPTS
                && now.duration_since(self.started_at) < VCT_ROOT_REPAIR_MAX_WALL_TIME)
        {
            return false;
        }

        self.exhausted = true;
        true
    }
}

#[derive(Clone, Debug, Default)]
pub(super) struct StaleAnchorFailures {
    pub(super) count: u32,
    pub(super) peers: HashSet<ZakuraPeerId>,
}

impl StaleAnchorFailures {
    pub(super) fn record(&mut self, peer: ZakuraPeerId) {
        self.count = self.count.saturating_add(1);
        self.peers.insert(peer);
    }

    pub(super) fn should_reanchor(&self) -> bool {
        self.count >= HEADER_SYNC_STALE_ANCHOR_LINK_FAILURES
            && self.peers.len() >= HEADER_SYNC_STALE_ANCHOR_DISTINCT_PEERS
    }

    pub(super) fn reset(&mut self) {
        self.count = 0;
        self.peers.clear();
    }
}

#[derive(Copy, Clone, Debug)]
pub(super) struct HeaderSyncAdvisoryPeerState {
    pub(super) summary: HeaderSyncServiceSummary,
    pub(super) observed_at: Instant,
    pub(super) failure_count: u32,
    pub(super) backoff_until: Option<Instant>,
}

impl HeaderSyncAdvisoryPeerState {
    pub(super) fn new(summary: HeaderSyncServiceSummary, observed_at: Instant) -> Self {
        Self {
            summary,
            observed_at,
            failure_count: 0,
            backoff_until: None,
        }
    }

    pub(super) fn refresh_summary(
        &mut self,
        summary: HeaderSyncServiceSummary,
        observed_at: Instant,
    ) {
        self.summary = summary;
        self.observed_at = observed_at;
    }

    pub(super) fn is_expired(&self, now: Instant) -> bool {
        now.duration_since(self.observed_at) >= HEADER_SYNC_ADVISORY_TTL
    }

    pub(super) fn is_backed_off(&self, now: Instant) -> bool {
        self.backoff_until.is_some_and(|until| until > now)
    }

    pub(super) fn record_confirmed(&mut self) {
        self.failure_count = 0;
        self.backoff_until = None;
    }

    pub(super) fn record_unconfirmed(&mut self, now: Instant) {
        self.failure_count = self.failure_count.saturating_add(1);
        if self.failure_count >= HEADER_SYNC_ADVISORY_BACKOFF_FAILURES {
            self.backoff_until = Some(now + HEADER_SYNC_ADVISORY_BACKOFF);
        }
    }
}

#[derive(Clone, Debug)]
pub(super) struct PeerHeaderState {
    pub(super) session: HeaderSyncPeerSession,
    pub(super) direction: ServicePeerDirection,
    pub(super) advertised_tip: block::Height,
    pub(super) advertised_hash: block::Hash,
    pub(super) anchor: block::Height,
    pub(super) max_headers_per_response: u32,
    pub(super) max_inflight_requests: u16,
    pub(super) received_status: bool,
    pub(super) last_received_status_at: Option<Instant>,
    /// The most recent status sent to this peer over its current session, if
    /// any. Used to suppress re-sending an identical, non-tip-advancing status,
    /// which the peer's inbound rate limiter would otherwise treat as spam.
    pub(super) last_sent_status: Option<HeaderSyncStatus>,
    pub(super) outstanding: Vec<OutstandingRange>,
    pub(super) meters: HeaderSyncPeerMeters,
    pub(super) served_headers_inflight: u16,
    pub(super) served_header_request_ids: HashSet<HeaderSyncRequestId>,
    pub(super) highest_served_header_request_id: Option<HeaderSyncRequestId>,
}

impl PeerHeaderState {
    pub(super) fn new(
        session: HeaderSyncPeerSession,
        anchor: (block::Height, block::Hash),
        local_range: u32,
        local_inflight: u16,
        status_refresh_interval: Duration,
        inbound_status_min_interval: Duration,
        inbound_new_block_min_interval: Duration,
    ) -> Self {
        Self {
            direction: session.direction(),
            session,
            advertised_tip: anchor.0,
            advertised_hash: anchor.1,
            anchor: anchor.0,
            max_headers_per_response: clamp_advertised_range(local_range),
            max_inflight_requests: local_inflight.clamp(1, LOCAL_MAX_HS_INFLIGHT_PER_PEER),
            received_status: false,
            last_received_status_at: None,
            last_sent_status: None,
            outstanding: Vec::new(),
            meters: HeaderSyncPeerMeters::new(
                status_refresh_interval,
                inbound_status_min_interval,
                inbound_new_block_min_interval,
            ),
            served_headers_inflight: 0,
            served_header_request_ids: HashSet::new(),
            highest_served_header_request_id: None,
        }
    }

    pub(super) fn available_slots(&self) -> usize {
        usize::from(self.max_inflight_requests).saturating_sub(self.outstanding.len())
    }

    pub(super) fn remove_outstanding_by_request_id(
        &mut self,
        request_id: HeaderSyncRequestId,
    ) -> Option<OutstandingRange> {
        self.outstanding
            .iter()
            .position(|outstanding| outstanding.request_id == request_id)
            .map(|index| self.outstanding.remove(index))
    }

    /// Whether `status` differs from the most recent status sent to this peer
    /// over its current session. A status identical to the last one we sent is
    /// redundant — the peer cannot learn anything from it and its inbound status
    /// rate limiter would treat it as spam — so callers suppress it.
    pub(super) fn status_differs_from_last_sent(&self, status: HeaderSyncStatus) -> bool {
        self.last_sent_status != Some(status)
    }

    /// Records `status` as the most recent status sent to this peer, so a later
    /// identical status can be suppressed by [`Self::status_differs_from_last_sent`].
    pub(super) fn record_sent_status(&mut self, status: HeaderSyncStatus) {
        self.last_sent_status = Some(status);
    }

    /// Forgets the last status sent to this peer so the next one is always sent.
    /// Called when a fresh session replaces the peer's transport: the new
    /// channel's remote has received no status yet and gates serving us on it,
    /// so the initial status must go out regardless of its contents.
    pub(super) fn reset_sent_status(&mut self) {
        self.last_sent_status = None;
    }

    pub(super) fn try_start_serving_headers(
        &mut self,
        local_inflight_cap: u16,
        request_id: HeaderSyncRequestId,
    ) -> bool {
        if self.served_headers_inflight >= local_inflight_cap {
            return false;
        }
        if self
            .highest_served_header_request_id
            .is_some_and(|highest| request_id.get() <= highest.get())
        {
            return false;
        }
        if !self.served_header_request_ids.insert(request_id) {
            return false;
        }
        self.highest_served_header_request_id = Some(request_id);
        self.served_headers_inflight = self.served_headers_inflight.saturating_add(1);
        true
    }

    pub(super) fn finish_serving_headers(&mut self, request_id: HeaderSyncRequestId) -> bool {
        if !self.served_header_request_ids.remove(&request_id) {
            return false;
        }
        self.served_headers_inflight = self.served_headers_inflight.saturating_sub(1);
        true
    }
}

#[derive(Clone, Debug)]
pub(super) struct HeaderSyncPeerMeters {
    pub(super) unsolicited: RateMeter,
    pub(super) inbound_status: RateMeter,
    pub(super) inbound_new_block: RateMeter,
    /// Gates redundant keepalive status sends.
    ///
    /// Floored above the remote's inbound status minimum interval so a
    /// keepalive can never be classified as status spam even when
    /// `status_refresh_interval` is configured below that minimum, and starts
    /// one full interval out so it never lands right after the initial
    /// connect status (which may already have consumed the remote's
    /// non-advancing status token).
    pub(super) keepalive: RateMeter,
}

impl HeaderSyncPeerMeters {
    pub(super) fn new(
        status_refresh_interval: Duration,
        inbound_status_min_interval: Duration,
        inbound_new_block_min_interval: Duration,
    ) -> Self {
        let keepalive_interval =
            status_refresh_interval.max(inbound_status_min_interval.saturating_mul(2));
        let mut keepalive = RateMeter::new(keepalive_interval);
        keepalive.mark_taken(Instant::now());
        Self {
            unsolicited: RateMeter::new(status_refresh_interval),
            inbound_status: RateMeter::new(inbound_status_min_interval),
            inbound_new_block: RateMeter::new(inbound_new_block_min_interval),
            keepalive,
        }
    }
}

#[derive(Copy, Clone, Debug)]
pub(super) struct OutstandingRange {
    pub(super) request_id: HeaderSyncRequestId,
    pub(super) range: RangeRequest,
    pub(super) deadline: Instant,
    pub(super) expected_max_count: u32,
    pub(super) clear_assignment_on_timeout: bool,
    pub(super) purpose: RangePurpose,
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub(super) struct RangeRequest {
    pub(super) start_height: block::Height,
    pub(super) count: u32,
    pub(super) anchor_hash: block::Hash,
    pub(super) finalized: bool,
    pub(super) want_tree_aux_roots: bool,
    pub(super) priority: RangePriority,
}

impl RangeRequest {
    pub(super) fn end_height(self) -> block::Height {
        height_after_count(self.start_height, self.count)
            .and_then(previous_height)
            .expect("range request count is non-zero")
    }

    pub(super) fn is_within(self, start: block::Height, end: block::Height) -> bool {
        self.start_height >= start && self.end_height() <= end
    }
}

#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub(super) enum RangePriority {
    Forward,
    Backward,
    Repair,
}

impl RangePriority {
    pub(super) fn label(self) -> &'static str {
        match self {
            RangePriority::Forward => "forward",
            RangePriority::Backward => "backward",
            RangePriority::Repair => "repair",
        }
    }
}

#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub(super) enum RangePurpose {
    Sync,
    VctRepair {
        height: block::Height,
        generation: u64,
    },
}