pos_ledger_db/schema/reward_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 LedgerInfoWithSignatures
9//! structure.
10//!
11//! Serialized LedgerInfoWithSignatures identified by `epoch`.
12//! ```text
13//! |<---key--->|<---------------value------------->|
14//! | epoch | ledger_info_with_signatures 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 crate::schema::{ensure_slice_len_eq, REWARD_EVENT_CF_NAME};
21use anyhow::Result;
22use byteorder::{BigEndian, ReadBytesExt};
23use diem_types::reward_distribution_event::{
24    RewardDistributionEventV1, RewardDistributionEventV2,
25};
26use schemadb::{
27    define_schema,
28    schema::{KeyCodec, ValueCodec},
29};
30use std::mem::size_of;
31
32define_schema!(
33    RewardEventSchema,
34    u64, /* epoch num */
35    RewardDistributionEventV2,
36    REWARD_EVENT_CF_NAME
37);
38
39impl KeyCodec<RewardEventSchema> 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<RewardEventSchema> for RewardDistributionEventV2 {
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)
55            // If `data` cannot be deserialized to `Self`, it may be stored in
56            // an older version.
57            .or(bcs::from_bytes::<RewardDistributionEventV1>(data)
58                .map(Into::into))
59            .map_err(Into::into)
60    }
61}