sc_consensus_subspace/
aux_schema.rs

1//! Schema for Subspace block weight in the aux-db.
2
3use parity_scale_codec::{Decode, Encode};
4use sc_client_api::backend::AuxStore;
5use sp_blockchain::{Error as ClientError, Result as ClientResult};
6use subspace_core_primitives::BlockWeight;
7
8fn load_decode<B, T>(backend: &B, key: &[u8]) -> ClientResult<Option<T>>
9where
10    B: AuxStore,
11    T: Decode,
12{
13    match backend.get_aux(key)? {
14        Some(t) => T::decode(&mut &t[..])
15            .map(Some)
16            .map_err(|e: parity_scale_codec::Error| {
17                ClientError::Backend(format!("Subspace DB is corrupted. Decode error: {e}"))
18            }),
19        None => Ok(None),
20    }
21}
22
23/// The aux storage key used to store the block weight of the given block hash.
24fn block_weight_key<H: Encode>(block_hash: H) -> Vec<u8> {
25    (b"block_weight", block_hash).encode()
26}
27
28/// Write the cumulative chain-weight of a block to aux storage.
29pub(crate) fn write_block_weight<H, F, R>(
30    block_hash: H,
31    block_weight: BlockWeight,
32    write_aux: F,
33) -> R
34where
35    H: Encode,
36    F: FnOnce(&[(Vec<u8>, &[u8])]) -> R,
37{
38    let key = block_weight_key(block_hash);
39    block_weight.using_encoded(|s| write_aux(&[(key, s)]))
40}
41
42/// Load the cumulative chain-weight associated with a block.
43pub(crate) fn load_block_weight<H: Encode, B: AuxStore>(
44    backend: &B,
45    block_hash: H,
46) -> ClientResult<Option<BlockWeight>> {
47    load_decode(backend, block_weight_key(block_hash).as_slice())
48}