zakura-state 7.0.0

State contextual verification and storage 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
//! Coherent, bounded RocksDB views used by startup recovery audits.

use super::*;

/// One RocksDB snapshot retained for a complete header-chain startup audit.
pub struct HeaderChainAuditSnapshot<'a> {
    store: &'a HeaderChainStore,
    snapshot: rocksdb::SnapshotWithThreadMode<'a, rocksdb::DB>,
}

impl HeaderChainAuditSnapshot<'_> {
    fn get_value<V: FallibleDiskValue<Error = HeaderChainValueError>>(
        &self,
        family: &'static str,
        key: impl AsRef<[u8]>,
    ) -> Result<Option<V>, StoreError> {
        let cf = self.store.cf(family).map_err(store_error)?;
        self.snapshot
            .get_cf(&cf, key.as_ref())
            .map_err(|_| StoreError::Unavailable("header-chain snapshot read failed"))?
            .map(|value| {
                V::decode(&value).map_err(|_| StoreError::Incoherent("invalid durable value"))
            })
            .transpose()
    }

    fn visit_raw(
        &self,
        collection: StoreCollection,
        family: &'static str,
        limit: RowLimit,
        visitor: &mut dyn FnMut(&[u8], &[u8]) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        let cf = self.store.cf(family).map_err(store_error)?;
        for (index, row) in self
            .snapshot
            .iterator_cf(&cf, rocksdb::IteratorMode::Start)
            .enumerate()
        {
            if index == limit.get() {
                return Err(StoreError::LimitExceeded { collection, limit });
            }
            let (key, value) =
                row.map_err(|_| StoreError::Unavailable("header-chain snapshot iterator failed"))?;
            visitor(&key, &value)?;
        }
        Ok(())
    }

    fn visit_projection(
        &self,
        collection: StoreCollection,
        family: &'static str,
        limit: RowLimit,
        visitor: &mut dyn FnMut(Frontier) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(collection, family, limit, &mut |key, value| {
            if key.len() != 4 || value.len() != 32 {
                return Err(StoreError::Incoherent("invalid projection row width"));
            }
            let height = HeaderHeightKey::from_bytes(key).0;
            let hash = block::Hash(
                value
                    .try_into()
                    .map_err(|_| StoreError::Incoherent("invalid projection hash"))?,
            );
            visitor(Frontier::new(height, hash))
        })
    }
}

impl StoreAuditRead for HeaderChainStore {
    type Snapshot<'a> = HeaderChainAuditSnapshot<'a>;

    fn audit_snapshot(&self) -> Result<Self::Snapshot<'_>, StoreError> {
        Ok(HeaderChainAuditSnapshot {
            store: self,
            snapshot: self.db.rocksdb_snapshot(),
        })
    }
}

impl StoreAuditSnapshot for HeaderChainAuditSnapshot<'_> {
    fn snapshot(&self) -> Result<EngineSnapshot, StoreError> {
        Ok(self.metadata()?.snapshot())
    }

    fn metadata(&self) -> Result<EngineMetadata, StoreError> {
        self.get_value(HEADER_ENGINE_META, METADATA_KEY)?
            .ok_or(StoreError::Unavailable("header-chain metadata is absent"))
    }

    fn visit_header_nodes(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(HeaderNode) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        let mut reasons_by_hash: HashMap<block::Hash, Vec<EligibilityReason>> = HashMap::new();
        let reason_limit = limit
            .get()
            .checked_mul(zakura_header_chain::MAX_DIRECT_ELIGIBILITY_REASONS_V1)
            .ok_or(StoreError::Incoherent(
                "eligibility-reason recovery limit overflow",
            ))?;
        self.visit_eligibility_roots(RowLimit::new(reason_limit), &mut |(hash, reason)| {
            reasons_by_hash.entry(hash).or_default().push(reason);
            Ok(())
        })?;
        self.visit_raw(
            StoreCollection::HeaderNodes,
            HEADER_NODE_BY_HASH,
            limit,
            &mut |key, value| {
                if key.len() != 32 {
                    return Err(StoreError::Incoherent("invalid node key width"));
                }
                let hash = block::Hash(
                    key.try_into()
                        .map_err(|_| StoreError::Incoherent("invalid node hash key"))?,
                );
                let disk = HeaderNodeDisk::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid durable node value"))?;
                if disk.hash != hash {
                    return Err(StoreError::Incoherent("node key/hash mismatch"));
                }
                let node = disk
                    .into_domain(reasons_by_hash.remove(&hash).unwrap_or_default())
                    .map_err(|_| StoreError::Incoherent("invalid durable node"))?;
                visitor(node)
            },
        )?;
        if !reasons_by_hash.is_empty() {
            return Err(StoreError::Incoherent("eligibility root has no node"));
        }
        Ok(())
    }

    fn visit_consensus_invalid_body_tombstones(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(
            zakura_header_chain::ConsensusInvalidBodyTombstone,
        ) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::ConsensusInvalidBodyTombstones,
            HEADER_CONSENSUS_INVALID_BODY_TOMBSTONE,
            limit,
            &mut |key, value| {
                if key.len() != 32 {
                    return Err(StoreError::Incoherent("invalid tombstone key width"));
                }
                let tombstone = zakura_header_chain::ConsensusInvalidBodyTombstone::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid tombstone value"))?;
                if key != tombstone.hash.0 {
                    return Err(StoreError::Incoherent("tombstone key/hash mismatch"));
                }
                visitor(tombstone)
            },
        )
    }

    fn consensus_invalid_body_tombstone_count(&self) -> Result<usize, StoreError> {
        let count = self
            .get_value::<HeaderRowCountDisk>(HEADER_ENGINE_META, TOMBSTONE_COUNT_KEY)?
            .ok_or(StoreError::Incoherent(
                "consensus-invalid tombstone count is absent",
            ))?;
        usize::try_from(count.0)
            .map_err(|_| StoreError::Incoherent("tombstone count does not fit usize"))
    }

    fn full_state_attests_to_body_validation_state(
        &self,
        header_hash: block::Hash,
        body_validation_state: &zakura_header_chain::BodyValidationState,
    ) -> Result<bool, StoreError> {
        let authority = self.get_value::<FullStateBodyValidationEvidenceAuthorityDisk>(
            HEADER_BODY_EVIDENCE_AUTHORITY,
            header_hash.0,
        )?;
        Ok(authority.is_some_and(|authority| {
            authority.attests_to_body_validation_state(header_hash, body_validation_state)
        }))
    }

    fn visit_header_child_edges(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut((block::Hash, block::Hash)) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::HeaderChildEdges,
            HEADER_CHILD,
            limit,
            &mut |key, value| {
                if key.len() != 64 || !value.is_empty() {
                    return Err(StoreError::Incoherent("invalid child-index row"));
                }
                let key = HeaderChildKey::from_bytes(key);
                visitor((key.parent, key.child))
            },
        )
    }

    fn visit_selected_projection(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(Frontier) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_projection(
            StoreCollection::SelectedProjection,
            HEADER_SELECTED,
            limit,
            visitor,
        )
    }

    fn visit_verified_projection(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(Frontier) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_projection(
            StoreCollection::VerifiedProjection,
            HEADER_VERIFIED,
            limit,
            visitor,
        )
    }

    fn visit_deferred_entries(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut((chrono::DateTime<Utc>, block::Hash)) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::DeferredHeaderEntries,
            HEADER_DEFERRED,
            limit,
            &mut |key, value| {
                if key.len() != 44 || !value.is_empty() {
                    return Err(StoreError::Incoherent("invalid deferred-index row"));
                }
                let key = HeaderDeferredKey::try_from_bytes(key)
                    .map_err(|_| StoreError::Incoherent("invalid deferred-index key"))?;
                let until = Utc
                    .timestamp_opt(key.seconds, key.nanoseconds)
                    .single()
                    .ok_or(StoreError::Incoherent("invalid deferred-index timestamp"))?;
                visitor((until, key.hash))
            },
        )
    }

    fn visit_eligibility_roots(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut((block::Hash, EligibilityReason)) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::EligibilityReasonRoots,
            HEADER_ELIGIBILITY_ROOT,
            limit,
            &mut |key, value| {
                let key = HeaderEligibilityRootKey::try_from_bytes(key)
                    .map_err(|_| StoreError::Incoherent("invalid eligibility-root key"))?;
                let reason = HeaderEligibilityReasonDisk::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid eligibility-root value"))?
                    .into_domain();
                if reason_kind(&reason) != key.kind || reason_evidence(&reason) != key.evidence {
                    return Err(StoreError::Incoherent(
                        "eligibility-root key/value mismatch",
                    ));
                }
                visitor((key.root, reason))
            },
        )
    }

    fn visit_aux_deliveries(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(UntrustedAuxDeliveryRow) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::AuxiliaryDeliveries,
            HEADER_AUX_DELIVERY,
            limit,
            &mut |key, value| {
                if key.len() != 64 {
                    return Err(StoreError::Incoherent("invalid auxiliary key width"));
                }
                let key = HeaderAuxDeliveryKey::from_bytes(key);
                let delivery = decode_untrusted_aux_delivery(value)
                    .map_err(|_| StoreError::Incoherent("invalid auxiliary value"))?;
                if delivery.delivery().header_hash != key.header
                    || delivery.delivery().delivery_id != key.delivery
                {
                    return Err(StoreError::Incoherent("auxiliary key/value mismatch"));
                }
                visitor(delivery)
            },
        )
    }

    fn visit_validation_context_records(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(ValidationContextRecord) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::ValidationContexts,
            HEADER_VALIDATION_CONTEXT,
            limit,
            &mut |key, value| {
                if key.len() != 32 {
                    return Err(StoreError::Incoherent(
                        "invalid validation-context key width",
                    ));
                }
                let hash = block::Hash(
                    key.try_into()
                        .map_err(|_| StoreError::Incoherent("invalid validation-context key"))?,
                );
                let record = HeaderValidationContextDisk::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid validation-context value"))?;
                if record.header.hash() != hash {
                    return Err(StoreError::Incoherent(
                        "validation-context key/hash mismatch",
                    ));
                }
                visitor(ValidationContextRecord {
                    header: record.header,
                    height: record.height,
                })
            },
        )
    }

    fn authenticated_canonical_hash(
        &self,
        height: block::Height,
    ) -> Result<Option<block::Hash>, StoreError> {
        let read_hash = |family, key: &[u8]| -> Result<Option<block::Hash>, StoreError> {
            let cf = self.store.cf(family).map_err(store_error)?;
            self.snapshot
                .get_cf(&cf, key)
                .map_err(|_| StoreError::Unavailable("canonical snapshot read failed"))
                .map(|value| value.map(block::Hash::from_bytes))
        };
        let hash = read_hash("hash_by_height", &height.as_bytes())?;
        if hash.is_some() {
            return Ok(hash);
        }
        read_hash("zakura_header_hash_by_height", &height.as_bytes())
    }

    fn finality_witness_header(
        &self,
        frontier: Frontier,
    ) -> Result<Option<zakura_header_chain::FinalityAncestryHeader>, StoreError> {
        let row = self.get_value::<HeaderFinalityWitnessDisk>(
            HEADER_FINALITY_WITNESS,
            HeaderFinalityWitnessKey {
                height: frontier.height,
                hash: frontier.hash,
            }
            .as_bytes(),
        )?;
        row.map(|row| {
            if row.context.height != frontier.height || row.context.header.hash() != frontier.hash {
                return Err(StoreError::Incoherent("finality witness key/hash mismatch"));
            }
            Ok(zakura_header_chain::FinalityAncestryHeader {
                header: row.context.header,
                frontier,
            })
        })
        .transpose()
    }

    fn finality_witness_count(&self) -> Result<usize, StoreError> {
        let count = self
            .get_value::<HeaderRowCountDisk>(HEADER_ENGINE_META, FINALITY_WITNESS_COUNT_KEY)?
            .ok_or(StoreError::Incoherent("finality witness count is absent"))?;
        usize::try_from(count.0)
            .map_err(|_| StoreError::Incoherent("finality witness count does not fit usize"))
    }

    fn visit_finality_witnesses(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(
            zakura_header_chain::FinalityAncestryHeader,
            u32,
            u32,
        ) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::FinalityHistory,
            HEADER_FINALITY_WITNESS,
            limit,
            &mut |key, value| {
                let key = HeaderFinalityWitnessKey::try_from_bytes(key)
                    .map_err(|_| StoreError::Incoherent("invalid finality witness key"))?;
                let row = HeaderFinalityWitnessDisk::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid finality witness value"))?;
                if row.context.height != key.height || row.context.header.hash() != key.hash {
                    return Err(StoreError::Incoherent(
                        "finality witness key/value mismatch",
                    ));
                }
                visitor(
                    zakura_header_chain::FinalityAncestryHeader {
                        header: row.context.header,
                        frontier: Frontier::new(row.context.height, key.hash),
                    },
                    row.root_references,
                    row.child_references,
                )
            },
        )
    }

    fn visit_finality_history(
        &self,
        limit: RowLimit,
        visitor: &mut dyn FnMut(FinalityRecord) -> Result<(), StoreError>,
    ) -> Result<(), StoreError> {
        self.visit_raw(
            StoreCollection::FinalityHistory,
            HEADER_FINALITY_HISTORY,
            limit,
            &mut |key, value| {
                if key.len() != 8 {
                    return Err(StoreError::Incoherent("invalid finality key width"));
                }
                let record = FinalityRecord::decode(value)
                    .map_err(|_| StoreError::Incoherent("invalid finality value"))?;
                if key != record.epoch.get().to_be_bytes() {
                    return Err(StoreError::Incoherent("finality key/value mismatch"));
                }
                visitor(record)
            },
        )
    }

    fn finality_history_checkpoint(&self) -> Result<Option<FinalityHistoryCheckpoint>, StoreError> {
        self.get_value(HEADER_ENGINE_META, FINALITY_HISTORY_CHECKPOINT_KEY)
    }

    fn finality_history_count(&self) -> Result<usize, StoreError> {
        let count = self
            .get_value::<HeaderRowCountDisk>(HEADER_ENGINE_META, FINALITY_HISTORY_COUNT_KEY)?
            .ok_or(StoreError::Incoherent("finality history count is absent"))?;
        usize::try_from(count.0)
            .map_err(|_| StoreError::Incoherent("finality history count does not fit usize"))
    }
}