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
use super::{error::*, events::*, wire::*, *};

pub(super) fn validate_anchor(
    network: &Network,
    anchor: (block::Height, block::Hash),
) -> Result<(), HeaderSyncStartError> {
    let expected = if anchor.0 == block::Height(0) {
        Some(network.genesis_hash())
    } else {
        network.checkpoint_list().hash(anchor.0)
    };
    match expected {
        Some(hash) if hash == anchor.1 => Ok(()),
        _ => Err(HeaderSyncStartError::InvalidAnchor { anchor }),
    }
}

pub(super) fn next_height(height: block::Height) -> Option<block::Height> {
    height.0.checked_add(1).map(block::Height)
}

pub(super) fn previous_height(height: block::Height) -> Option<block::Height> {
    height.0.checked_sub(1).map(block::Height)
}

pub(super) fn height_after_count(start: block::Height, count: u32) -> Option<block::Height> {
    start.0.checked_add(count).map(block::Height)
}

pub(super) fn count_between(start: block::Height, end: block::Height) -> u32 {
    end.0
        .checked_sub(start.0)
        .and_then(|diff| diff.checked_add(1))
        .unwrap_or(0)
}

pub(super) fn insert_peer(
    row: &mut serde_json::Map<String, Value>,
    key: &'static str,
    peer: &ZakuraPeerId,
) {
    row.insert(key.to_string(), Value::String(trace_peer_label(peer)));
}

pub(super) fn insert_height(
    row: &mut serde_json::Map<String, Value>,
    key: &'static str,
    height: block::Height,
) {
    insert_u64(row, key, u64::from(height.0));
}

pub(super) fn insert_hash(
    row: &mut serde_json::Map<String, Value>,
    key: &'static str,
    hash: block::Hash,
) {
    row.insert(key.to_string(), Value::String(format!("{hash}")));
}

pub(super) fn insert_u64(row: &mut serde_json::Map<String, Value>, key: &'static str, value: u64) {
    row.insert(key.to_string(), Value::Number(Number::from(value)));
}

pub(super) fn insert_bool(
    row: &mut serde_json::Map<String, Value>,
    key: &'static str,
    value: bool,
) {
    row.insert(key.to_string(), Value::Bool(value));
}

pub(super) fn insert_optional_str(
    row: &mut serde_json::Map<String, Value>,
    key: &'static str,
    value: Option<&'static str>,
) {
    row.insert(
        key.to_string(),
        value.map_or(Value::Null, |value| Value::String(value.to_string())),
    );
}

pub(super) fn misbehavior_reason_label(reason: HeaderSyncMisbehavior) -> &'static str {
    match reason {
        HeaderSyncMisbehavior::InvalidStatus => "invalid_status",
        HeaderSyncMisbehavior::UnsolicitedHeaders => "unsolicited_headers",
        HeaderSyncMisbehavior::EmptyHeaders => "empty_headers",
        HeaderSyncMisbehavior::ResponseTooLong => "response_too_long",
        HeaderSyncMisbehavior::InvalidRange => "invalid_range",
        HeaderSyncMisbehavior::MalformedMessage => "malformed_message",
        HeaderSyncMisbehavior::StatusSpam => "status_spam",
        HeaderSyncMisbehavior::NewBlockSpam => "new_block_spam",
        HeaderSyncMisbehavior::GetHeadersSpam => "get_headers_spam",
        HeaderSyncMisbehavior::GetHeadersTooLong => "get_headers_too_long",
        HeaderSyncMisbehavior::UnknownPeer => "unknown_peer",
        HeaderSyncMisbehavior::InvalidNewBlock => "invalid_new_block",
    }
}

pub(super) fn commit_failure_reason_label(kind: HeaderSyncCommitFailureKind) -> &'static str {
    match kind {
        HeaderSyncCommitFailureKind::InvalidPeerRange => "invalid_peer_range",
        HeaderSyncCommitFailureKind::Local => "local",
    }
}

/// Peer/request bounds required to decode a header response without over-allocation.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub struct HeaderSyncDecodeContext {
    /// The matching in-flight request, when a `Headers` response is expected.
    pub requested: Option<ExpectedHeadersResponse>,
    /// Peer's advertised response cap.
    pub peer_max_headers_per_response: u32,
}

impl HeaderSyncDecodeContext {
    /// Context for messages that are not `Headers` responses.
    pub fn control() -> Self {
        Self {
            requested: None,
            peer_max_headers_per_response: DEFAULT_HS_RANGE,
        }
    }

    /// Context for a `Headers` response to `requested`.
    pub fn for_headers_response(
        requested: ExpectedHeadersResponse,
        peer_max_headers_per_response: u32,
    ) -> Self {
        Self {
            requested: Some(requested),
            peer_max_headers_per_response: clamp_advertised_range(peer_max_headers_per_response),
        }
    }

    pub(super) fn wants_tree_aux_roots(self) -> bool {
        self.requested
            .is_some_and(|requested| requested.want_tree_aux_roots)
    }

    pub(super) fn headers_response_limit(self) -> Result<Option<usize>, HeaderSyncWireError> {
        let Some(requested) = self.requested else {
            return Ok(None);
        };
        let cap = min(
            min(requested.count, self.peer_max_headers_per_response),
            MAX_HS_RANGE,
        );
        Some(usize_from_u32(cap, "headers response limit")).transpose()
    }
}

/// Stateless header validation context.
#[derive(Copy, Clone, Debug)]
pub struct HeaderSyncValidationContext<'a> {
    /// Active network, used for Equihash solution-size policy.
    pub network: &'a Network,
    /// Wall clock used for future-time checks.
    pub now: DateTime<Utc>,
    /// First height in the received run.
    pub start_height: block::Height,
    /// Matching request and peer cap for count validation.
    pub decode_context: HeaderSyncDecodeContext,
}

/// Run all context-free validation checks for an inbound `Headers` response.
#[tracing::instrument(skip(headers, context))]
pub async fn validate_headers_stateless(
    headers: Vec<Arc<block::Header>>,
    context: HeaderSyncValidationContext<'_>,
) -> Result<(), HeaderSyncWireError> {
    validate_header_count(headers.len(), context.decode_context)?;
    validate_internal_continuity(&headers)?;
    validate_header_times(&headers, context.now, context.start_height)?;
    validate_solution_sizes(&headers, context.network)?;
    validate_pow_spawn_blocking(headers, context.network).await
}

/// Check that a header range links to its anchor and is internally contiguous.
pub fn validate_header_range_links(
    anchor: block::Hash,
    headers: &[Arc<block::Header>],
) -> Result<(), HeaderSyncWireError> {
    let Some(first) = headers.first() else {
        return Ok(());
    };

    if first.previous_block_hash != anchor {
        return Err(HeaderSyncWireError::FirstHeaderDoesNotLink);
    }

    validate_internal_continuity(headers)
}

/// Run all context-free validation checks for an inbound full-block tip flood.
#[tracing::instrument(skip(block, network))]
pub async fn validate_new_block_stateless(
    block: Arc<block::Block>,
    network: &Network,
    now: DateTime<Utc>,
    height: block::Height,
) -> Result<(), HeaderSyncWireError> {
    let header = block.header.clone();
    validate_header_times(std::slice::from_ref(&header), now, height)?;
    validate_solution_sizes(std::slice::from_ref(&header), network)?;
    validate_pow_spawn_blocking(vec![header], network).await
}

pub(super) fn validate_header_count(
    len: usize,
    context: HeaderSyncDecodeContext,
) -> Result<(), HeaderSyncWireError> {
    let Some(max_headers) = context.headers_response_limit()? else {
        return Err(HeaderSyncWireError::UnsolicitedHeaders);
    };
    validate_headers_len(len, max_headers)
}

pub(super) fn validate_internal_continuity(
    headers: &[Arc<block::Header>],
) -> Result<(), HeaderSyncWireError> {
    for adjacent in headers.windows(2) {
        let previous_hash = block::Hash::from(adjacent[0].as_ref());
        if previous_hash != adjacent[1].previous_block_hash {
            return Err(HeaderSyncWireError::NonContiguousHeaders);
        }
    }
    Ok(())
}

pub(super) fn validate_header_times(
    headers: &[Arc<block::Header>],
    now: DateTime<Utc>,
    start_height: block::Height,
) -> Result<(), HeaderSyncWireError> {
    for (offset, header) in headers.iter().enumerate() {
        let offset = u32::try_from(offset)
            .map_err(|_| HeaderSyncWireError::NumericOverflow("header height offset"))?;
        let height = block::Height(
            start_height
                .0
                .checked_add(offset)
                .ok_or(HeaderSyncWireError::NumericOverflow("header height"))?,
        );
        let hash = block::Hash::from(header.as_ref());
        header.time_is_valid_at(now, &height, &hash)?;
    }
    Ok(())
}

pub(super) fn validate_solution_sizes(
    headers: &[Arc<block::Header>],
    network: &Network,
) -> Result<(), HeaderSyncWireError> {
    let expect_regtest = network
        .parameters()
        .is_some_and(|parameters| parameters.is_regtest());
    for header in headers {
        match (expect_regtest, header.solution) {
            (true, equihash::Solution::Regtest(_))
            | (true, equihash::Solution::Common(_))
            | (false, equihash::Solution::Common(_)) => {}
            _ => return Err(HeaderSyncWireError::WrongEquihashSolutionSize),
        }
    }
    Ok(())
}

pub(super) async fn validate_pow_spawn_blocking(
    headers: Vec<Arc<block::Header>>,
    network: &Network,
) -> Result<(), HeaderSyncWireError> {
    let network = network.clone();
    tokio::task::spawn_blocking(move || validate_pow_blocking(&headers, &network)).await?
}

pub(super) fn validate_pow_blocking(
    headers: &[Arc<block::Header>],
    network: &Network,
) -> Result<(), HeaderSyncWireError> {
    let skip_pow_filter = network
        .parameters()
        .is_some_and(|parameters| parameters.is_regtest());
    if skip_pow_filter {
        return Ok(());
    }

    for header in headers {
        // Bind the Equihash parameters to `network` so a short 36-byte
        // Regtest-shaped solution cannot pass the PoW check on Mainnet/Testnet.
        header.solution.check(header, network)?;
        let hash = block::Hash::from(header.as_ref());
        validate_difficulty_filter(hash, header.difficulty_threshold)?;
    }
    Ok(())
}

pub(super) fn validate_difficulty_filter(
    hash: block::Hash,
    difficulty_threshold: CompactDifficulty,
) -> Result<(), HeaderSyncWireError> {
    let threshold = difficulty_threshold
        .to_expanded()
        .ok_or(HeaderSyncWireError::InvalidDifficultyThreshold)?;
    if hash > threshold {
        return Err(HeaderSyncWireError::DifficultyFilter { hash, threshold });
    }
    Ok(())
}

pub(super) fn validate_get_headers_count(count: u32) -> Result<(), HeaderSyncWireError> {
    if count == 0 {
        return Err(HeaderSyncWireError::ZeroHeaderRequestCount);
    }
    if count > MAX_HS_RANGE {
        return Err(HeaderSyncWireError::HeaderCountLimit {
            actual: usize_from_u32(count, "headers count")?,
            max: usize_from_u32(MAX_HS_RANGE, "headers cap")?,
        });
    }
    Ok(())
}

pub(super) fn validate_headers_len(len: usize, max: usize) -> Result<(), HeaderSyncWireError> {
    if len > max {
        return Err(HeaderSyncWireError::HeaderCountLimit { actual: len, max });
    }
    Ok(())
}

pub(super) fn validate_body_sizes_len(
    headers: usize,
    body_sizes: usize,
) -> Result<(), HeaderSyncWireError> {
    if headers != body_sizes {
        return Err(HeaderSyncWireError::BodySizeCountMismatch {
            headers,
            body_sizes,
        });
    }
    Ok(())
}

pub(super) fn validate_tree_aux_roots_len(
    headers: usize,
    roots: usize,
) -> Result<(), HeaderSyncWireError> {
    if headers != roots {
        return Err(HeaderSyncWireError::TreeAuxRootCountMismatch { headers, roots });
    }
    Ok(())
}

pub(super) fn validate_tree_aux_root_heights(
    start_height: block::Height,
    roots: &[BlockCommitmentRoots],
) -> Result<(), HeaderSyncWireError> {
    for (offset, root) in roots.iter().enumerate() {
        let height_offset = u32::try_from(offset)
            .map_err(|_| HeaderSyncWireError::NumericOverflow("tree-aux root height offset"))?;
        let expected_height = block::Height(
            start_height
                .0
                .checked_add(height_offset)
                .ok_or(HeaderSyncWireError::NumericOverflow("tree-aux root height"))?,
        );
        if root.height != expected_height {
            return Err(HeaderSyncWireError::TreeAuxRootHeightMismatch {
                offset,
                expected_height,
                root_height: root.height,
                first_root_height: roots
                    .first()
                    .expect("a mismatching root exists because the loop is processing it")
                    .height,
                last_root_height: roots
                    .last()
                    .expect("a mismatching root exists because the loop is processing it")
                    .height,
            });
        }
    }
    Ok(())
}

pub(super) fn clamp_advertised_range(value: u32) -> u32 {
    value.clamp(1, MAX_HS_RANGE)
}

pub(super) fn write_height<W: Write>(
    writer: &mut W,
    height: block::Height,
) -> Result<(), HeaderSyncWireError> {
    writer.write_u32::<LittleEndian>(height.0)?;
    Ok(())
}

pub(super) fn read_height<R: Read>(reader: &mut R) -> Result<block::Height, HeaderSyncWireError> {
    let height = block::Height(reader.read_u32::<LittleEndian>()?);
    if height > block::Height::MAX {
        return Err(HeaderSyncWireError::HeightOutOfRange(height.0));
    }
    Ok(height)
}

pub(super) fn read_bool_marker<R: Read>(
    reader: &mut R,
    field: &'static str,
) -> Result<bool, HeaderSyncWireError> {
    match reader.read_u8()? {
        0 => Ok(false),
        1 => Ok(true),
        value => Err(HeaderSyncWireError::InvalidBoolMarker { field, value }),
    }
}

pub(super) fn reject_trailing(
    bytes: &[u8],
    reader: &Cursor<&[u8]>,
) -> Result<(), HeaderSyncWireError> {
    let consumed = usize::try_from(reader.position())
        .map_err(|_| HeaderSyncWireError::NumericOverflow("cursor position"))?;
    if consumed != bytes.len() {
        return Err(HeaderSyncWireError::TrailingBytes);
    }
    Ok(())
}

pub(super) fn usize_from_u32(
    value: u32,
    field: &'static str,
) -> Result<usize, HeaderSyncWireError> {
    usize::try_from(value).map_err(|_| HeaderSyncWireError::NumericOverflow(field))
}

pub(super) fn u32_from_usize(
    value: usize,
    field: &'static str,
) -> Result<u32, HeaderSyncWireError> {
    u32::try_from(value).map_err(|_| HeaderSyncWireError::NumericOverflow(field))
}