cfxcore/pos/consensus/consensusdb/schema/staking_event/
mod.rs

1// Copyright (c) The Diem Core Contributors
2// SPDX-License-Identifier: Apache-2.0
3
4// Copyright 2021 Conflux Foundation. All rights reserved.
5// Conflux is free software and distributed under GNU General Public License.
6// See http://www.gnu.org/licenses/
7
8//! This module defines physical storage schema for StakingEvents
9//! structure.
10//!
11//! Serialized StakingEvents identified by `epoch`.
12//! ```text
13//! |<---key--->|<---------------value------------->|
14//! | epoch | staking_events bytes |
15//! ```
16//!
17//! `epoch` is serialized in big endian so that records in RocksDB will be in
18//! order of their numeric value.
19
20use super::STAKING_EVENTS_CF_NAME;
21use crate::pos::consensus::consensusdb::schema::ensure_slice_len_eq;
22use anyhow::Result;
23use byteorder::{BigEndian, ReadBytesExt};
24use cfx_types::H256;
25use pow_types::StakingEvent;
26use schemadb::{
27    define_schema,
28    schema::{KeyCodec, ValueCodec},
29};
30use std::mem::size_of;
31
32define_schema!(
33    StakingEventsSchema,
34    u64, /* block id */
35    (Vec<StakingEvent>, H256),
36    STAKING_EVENTS_CF_NAME
37);
38
39impl KeyCodec<StakingEventsSchema> for u64 {
40    fn encode_key(&self) -> Result<Vec<u8>> { Ok(self.to_be_bytes().to_vec()) }
41
42    fn decode_key(mut data: &[u8]) -> Result<Self> {
43        ensure_slice_len_eq(data, size_of::<Self>())?;
44        Ok(data.read_u64::<BigEndian>()?)
45    }
46}
47
48impl ValueCodec<StakingEventsSchema> for (Vec<StakingEvent>, H256) {
49    fn encode_value(&self) -> Result<Vec<u8>> {
50        bcs::to_bytes(self).map_err(Into::into)
51    }
52
53    fn decode_value(data: &[u8]) -> Result<Self> {
54        bcs::from_bytes(data).map_err(Into::into)
55    }
56}