hotshot_types/traits/
storage.rs

1// Copyright (c) 2021-2024 Espresso Systems (espressosys.com)
2// This file is part of the HotShot repository.
3
4// You should have received a copy of the MIT License
5// along with the HotShot repository. If not, see <https://mit-license.org/>.
6
7//! Abstract storage type for storing DA proposals and VID shares
8//!
9//! This modules provides the [`Storage`] trait.
10//!
11
12use std::sync::Arc;
13
14use anyhow::Result;
15use async_trait::async_trait;
16use futures::future::BoxFuture;
17
18use super::node_implementation::NodeType;
19use crate::{
20    data::{
21        vid_disperse::{ADVZDisperseShare, VidDisperseShare2},
22        DaProposal, DaProposal2, QuorumProposal, QuorumProposal2, QuorumProposalWrapper,
23        VidCommitment, VidDisperseShare,
24    },
25    drb::{DrbInput, DrbResult},
26    event::HotShotAction,
27    message::{convert_proposal, Proposal},
28    simple_certificate::{
29        LightClientStateUpdateCertificate, NextEpochQuorumCertificate2, QuorumCertificate,
30        QuorumCertificate2, UpgradeCertificate,
31    },
32};
33
34/// Abstraction for storing a variety of consensus payload datum.
35#[async_trait]
36pub trait Storage<TYPES: NodeType>: Send + Sync + Clone + 'static {
37    /// Add a proposal to the stored VID proposals.
38    async fn append_vid(&self, proposal: &Proposal<TYPES, ADVZDisperseShare<TYPES>>) -> Result<()>;
39    /// Add a proposal to the stored VID proposals.
40    /// TODO(Chengyu): fix this
41    async fn append_vid2(&self, proposal: &Proposal<TYPES, VidDisperseShare2<TYPES>>)
42        -> Result<()>;
43
44    async fn append_vid_general(
45        &self,
46        proposal: &Proposal<TYPES, VidDisperseShare<TYPES>>,
47    ) -> Result<()> {
48        let signature = proposal.signature.clone();
49        match &proposal.data {
50            VidDisperseShare::V0(share) => {
51                self.append_vid(&Proposal {
52                    data: share.clone(),
53                    signature,
54                    _pd: std::marker::PhantomData,
55                })
56                .await
57            },
58            VidDisperseShare::V1(share) => {
59                self.append_vid2(&Proposal {
60                    data: share.clone(),
61                    signature,
62                    _pd: std::marker::PhantomData,
63                })
64                .await
65            },
66        }
67    }
68    /// Add a proposal to the stored DA proposals.
69    async fn append_da(
70        &self,
71        proposal: &Proposal<TYPES, DaProposal<TYPES>>,
72        vid_commit: VidCommitment,
73    ) -> Result<()>;
74    /// Add a proposal to the stored DA proposals.
75    async fn append_da2(
76        &self,
77        proposal: &Proposal<TYPES, DaProposal2<TYPES>>,
78        vid_commit: VidCommitment,
79    ) -> Result<()> {
80        self.append_da(&convert_proposal(proposal.clone()), vid_commit)
81            .await
82    }
83    /// Add a proposal we sent to the store
84    async fn append_proposal(
85        &self,
86        proposal: &Proposal<TYPES, QuorumProposal<TYPES>>,
87    ) -> Result<()>;
88    /// Add a proposal we sent to the store
89    async fn append_proposal2(
90        &self,
91        proposal: &Proposal<TYPES, QuorumProposal2<TYPES>>,
92    ) -> Result<()>;
93    /// Add a proposal we sent to the store
94    async fn append_proposal_wrapper(
95        &self,
96        proposal: &Proposal<TYPES, QuorumProposalWrapper<TYPES>>,
97    ) -> Result<()> {
98        self.append_proposal2(&convert_proposal(proposal.clone()))
99            .await
100    }
101    /// Record a HotShotAction taken.
102    async fn record_action(
103        &self,
104        view: TYPES::View,
105        epoch: Option<TYPES::Epoch>,
106        action: HotShotAction,
107    ) -> Result<()>;
108    /// Update the current high QC in storage.
109    async fn update_high_qc(&self, high_qc: QuorumCertificate<TYPES>) -> Result<()>;
110    /// Update the current high QC in storage.
111    async fn update_high_qc2(&self, high_qc: QuorumCertificate2<TYPES>) -> Result<()> {
112        self.update_high_qc(high_qc.to_qc()).await
113    }
114    /// Update the light client state update certificate in storage.
115    async fn update_state_cert(
116        &self,
117        state_cert: LightClientStateUpdateCertificate<TYPES>,
118    ) -> Result<()>;
119
120    async fn update_high_qc2_and_state_cert(
121        &self,
122        high_qc: QuorumCertificate2<TYPES>,
123        state_cert: LightClientStateUpdateCertificate<TYPES>,
124    ) -> Result<()> {
125        self.update_high_qc2(high_qc).await?;
126        self.update_state_cert(state_cert).await
127    }
128    /// Update the current high QC in storage.
129    async fn update_next_epoch_high_qc2(
130        &self,
131        _next_epoch_high_qc: NextEpochQuorumCertificate2<TYPES>,
132    ) -> Result<()> {
133        Ok(())
134    }
135
136    /// Upgrade the current decided upgrade certificate in storage.
137    async fn update_decided_upgrade_certificate(
138        &self,
139        decided_upgrade_certificate: Option<UpgradeCertificate<TYPES>>,
140    ) -> Result<()>;
141    /// Migrate leaves from `Leaf` to `Leaf2`, and proposals from `QuorumProposal` to `QuorumProposal2`
142    async fn migrate_consensus(&self) -> Result<()> {
143        Ok(())
144    }
145    /// Add a drb result
146    async fn add_drb_result(&self, epoch: TYPES::Epoch, drb_result: DrbResult) -> Result<()>;
147    /// Add an epoch block header
148    async fn add_epoch_root(
149        &self,
150        epoch: TYPES::Epoch,
151        block_header: TYPES::BlockHeader,
152    ) -> Result<()>;
153    async fn add_drb_input(&self, _epoch: u64, _iteration: u64, _drb_input: [u8; 32]) {}
154    async fn load_drb_input(&self, _epoch: u64) -> Result<DrbInput> {
155        Err(anyhow::anyhow!("load_drb_input unimplemented"))
156    }
157}
158
159pub async fn store_drb_input_impl<TYPES: NodeType>(
160    storage: impl Storage<TYPES>,
161    epoch: u64,
162    iteration: u64,
163    value: [u8; 32],
164) {
165    storage.add_drb_input(epoch, iteration, value).await
166}
167
168pub type StoreDrbProgressFn =
169    std::sync::Arc<dyn Fn(u64, u64, DrbResult) -> BoxFuture<'static, ()> + Send + Sync>;
170
171pub fn store_drb_progress_fn<TYPES: NodeType>(
172    storage: impl Storage<TYPES> + 'static,
173) -> StoreDrbProgressFn {
174    Arc::new(move |epoch, iteration, value| {
175        let storage = storage.clone();
176        Box::pin(store_drb_input_impl(storage, epoch, iteration, value))
177    })
178}
179
180pub fn null_store_drb_progress_fn() -> StoreDrbProgressFn {
181    Arc::new(move |_epoch, _iteration, _value| Box::pin(async {}))
182}
183
184pub type StorageAddDrbResultFn<TYPES> = Arc<
185    Box<
186        dyn Fn(<TYPES as NodeType>::Epoch, DrbResult) -> BoxFuture<'static, Result<()>>
187            + Send
188            + Sync
189            + 'static,
190    >,
191>;
192
193async fn storage_add_drb_result_impl<TYPES: NodeType>(
194    storage: impl Storage<TYPES>,
195    epoch: TYPES::Epoch,
196    drb_result: DrbResult,
197) -> Result<()> {
198    storage.add_drb_result(epoch, drb_result).await
199}
200
201/// Helper function to create a callback to add a drb result to storage
202pub fn storage_add_drb_result<TYPES: NodeType>(
203    storage: impl Storage<TYPES> + 'static,
204) -> StorageAddDrbResultFn<TYPES> {
205    Arc::new(Box::new(move |epoch, drb_result| {
206        let st = storage.clone();
207        Box::pin(storage_add_drb_result_impl(st, epoch, drb_result))
208    }))
209}